Product of Array Except Self
Master this topic with zero to advance depth.
Product of Array Except Self
The product of all elements except nums[i] is (product of all elements to the left of i) * (product of all elements to the right of i). We can precalculate these products in one or two passes.
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 operator.
Visual Representation
nums = [1, 2, 3, 4]
Prefixes: [1, 1, 1*2, 1*2*3] = [1, 1, 2, 6]
Suffixes: [2*3*4, 3*4, 4, 1] = [24, 12, 4, 1]
Result: [1*24, 1*12, 2*4, 6*1] = [24, 12, 8, 6]Examples
answer[0] = 234 = 24, answer[1] = 134 = 12, answer[2] = 124 = 8, answer[3] = 123 = 6
Any product that includes 0 will be 0
Level I: Brute Force (Nested Loops)
Intuition
For each index i, we iterate through the entire array again using index j. If i != j, we multiply nums[j] to a running product. This is suboptimal due to the nested traversal.
Detailed Dry Run
| Index | Elements Multiplied | Result |
|---|---|---|
| 0 | 2 * 3 * 4 | 24 |
| 1 | 1 * 3 * 4 | 12 |
| 2 | 1 * 2 * 4 | 8 |
| 3 | 1 * 2 * 3 | 6 |
Level II: Better Solution (Prefix & Suffix Arrays)
Intuition
Any element at i has a product equal to (everything to its left) * (everything to its right). We can precompute two arrays: prefix (cumulative product from start) and suffix (cumulative product from end).
Detailed Dry Run
| Index | Prefix (Left) | Suffix (Right) | Left * Right |
|---|---|---|---|
| 0 | 1 | 234 = 24 | 24 |
| 1 | 1 | 3*4 = 12 | 12 |
| 2 | 1*2 = 2 | 4 | 8 |
| 3 | 123 = 6 | 1 | 6 |
Level III: Optimal Solution (Space Optimized)
Intuition
We can optimize space by using the result array itself to store prefix products first. Then, we iterate backwards and maintain a running suffix product to multiply with the stored prefix values. This avoids extra arrays.
Detailed Dry Run
Optimization Visual
nums = [1, 2, 3, 4]
Forward Pass (Prefix):
res = [1, 1, 2, 6] (Storing products of everything to the left)
Backward Pass (Suffix):
| i | res[i] (Prefix) | Suffix Var | res[i] * Suffix (Final) |
|---|---|---|---|
| 3 | 6 | 1 | 6 |
| 2 | 2 | 1*4=4 | 8 |
| 1 | 1 | 4*3=12 | 12 |
| 0 | 1 | 12*2=24 | 24 |
Visual Representation:
Index: 0 1 2 3
Nums: 1 2 3 4
Prefix: [1, 1, 2, 6]
Suffix: [24, 12, 4, 1]
Result: [24, 12, 8, 6]Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.