Product of Array Except Self – Solution & Complexity
Watch: Product of Array Except Self with prefix and suffix products
Every answer is the product of everything to its left times everything to its right. One pass left to right writes the running prefix product into the output before folding in the current number; a second pass right to left multiplies in the running suffix product. O(n) time, O(1) extra space, no division, and zeros need no special case.
Solution Walkthrough
Step 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.
- For each index
Step 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²).
Step 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.
Step 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].
- Start with an answer array filled with
Step 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.