Product of Array Except Self – Solution & Complexity
1. Understand Each Output Position
- For each index
i, the answer should be the product of every number exceptnums[i]. - Division is not allowed, so we cannot compute one total product and divide by the current value.
- The output order must match the input order exactly.
2. Consider the Brute Force Idea
- For each index, multiply all values at every other index.
- This is correct and handles zeroes, but it repeats almost the same multiplication for every position.
- The nested loops make the time complexity O(n²).
3. Split the Product into Left and Right Parts
- The product except self is the product of everything to the left times everything to the right.
- A prefix pass can store products before each index.
- A suffix pass can multiply in products after each index.
4. Fill Prefix Products First
- Start with an answer array filled with
1. - Move left to right while carrying a running prefix product.
- Before multiplying by
nums[i], store the product of all values to the left inanswer[i].
5. Final Solution and Complexity
- The second pass moves right to left with a running suffix product.
- Multiplying
answer[i]by the suffix gives left product times right product, excludingnums[i]itself. - Time complexity is O(n), and extra space is O(1) besides the required output array.