The provided solution is implemented in C++ and uses two passes through the nums
array to calculate the answer
vector without using division.
-
Initialization:
- Initialize an empty vector
answer
. - Initialize two variables
m
andm1
to 1, which will be used to track the product of non-zero elements and all elements, respectively. - Initialize a variable
count
to keep track of the number of zeros in the array.
- Initialize an empty vector
-
First Pass:
- Iterate through the
nums
array. - For each element
nums[i]
, add it to theanswer
vector. - Update
m
andm1
by multiplying them with the current elementnums[i]
. - If the current element is 0, increment the
count
variable.
- Iterate through the
-
Second Pass:
- Iterate through the
nums
array again. - For each element at index
i
, calculate the value foranswer[i]
based on the following conditions:- If
count
is greater than 1 (meaning there are more than one zero in the array), setanswer[i]
to 0 because the product of all elements would be 0. - If
nums[i]
is 0, setanswer[i]
tom1
. This is because the product of all elements except the zero element is equal tom1
. - Otherwise, set
answer[i]
to the result of dividingm
bynums[i
, which effectively gives the product of all elements except the current one.
- If
- Iterate through the
-
Return:
- Return the
answer
vector, which contains the desired result.
- Return the
The provided solution correctly handles different cases and satisfies the O(n) time complexity constraint, but it uses O(n) extra space to store the answer
vector. Achieving O(1) extra space complexity would require a different approach, such as using prefix and suffix products with careful computation.