Product of Array Except Self medium
Problem Statement
Given an integer array nums
, return *an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
.
The product of any prefix or suffix of nums
is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Explanation: The product of all elements except nums[i]
is calculated as follows:
answer[0]
= 2 * 3 * 4 = 24answer[1]
= 1 * 3 * 4 = 12answer[2]
= 1 * 2 * 4 = 8answer[3]
= 1 * 2 * 3 = 6
Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Steps and Explanation
The key to solving this problem efficiently (in O(n) time) without division is to calculate the prefix and suffix products separately. We'll do this in two passes:
-
Prefix Pass: Create an array
prefix_prod
whereprefix_prod[i]
stores the product of all elements beforenums[i]
.prefix_prod[0]
will be 1 (there are no elements before the first element). -
Suffix Pass: Create an array
suffix_prod
wheresuffix_prod[i]
stores the product of all elements afternums[i]
.suffix_prod[n-1]
will be 1 (there are no elements after the last element). -
Result: The final result
answer[i]
is simplyprefix_prod[i] * suffix_prod[i]
.
Code
#include <vector>
std::vector<int> productExceptSelf(std::vector<int>& nums) {
int n = nums.size();
std::vector<int> prefix_prod(n, 1);
std::vector<int> suffix_prod(n, 1);
std::vector<int> answer(n);
// Prefix pass
for (int i = 1; i < n; ++i) {
prefix_prod[i] = prefix_prod[i - 1] * nums[i - 1];
}
// Suffix pass
for (int i = n - 2; i >= 0; --i) {
suffix_prod[i] = suffix_prod[i + 1] * nums[i + 1];
}
// Calculate the final result
for (int i = 0; i < n; ++i) {
answer[i] = prefix_prod[i] * suffix_prod[i];
}
return answer;
}
Complexity
- Time Complexity: O(n), as we iterate through the array three times.
- Space Complexity: O(n), to store the
prefix_prod
,suffix_prod
, andanswer
arrays. We could optimize space slightly by not creatingprefix_prod
andsuffix_prod
explicitly and storing intermediate results directly inanswer
, but this would make the code less readable.