Product of Array Except Self
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].
Examples
nums = [1,2,3,4]
[24,12,8,6]
answer[0] = 2*3*4 = 24, answer[1] = 1*3*4 = 12, etc.
nums = [-1,1,0,-3,3]
[0,0,9,0,0]
Products involving 0 become 0.
Constraints
- •
2 <= nums.length <= 10^5 - •
-30 <= nums[i] <= 30 - •
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
Approaches
For each element, compute the product of all other elements.
def product_except_self(nums):
n = len(nums)
result = [1] * n
for i in range(n):
for j in range(n):
if i != j:
result[i] *= nums[j]
return resultCompute prefix products and suffix products, then multiply them.
def product_except_self(nums):
n = len(nums)
prefix = [1] * n
suffix = [1] * n
for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]
for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * nums[i+1]
return [prefix[i] * suffix[i] for i in range(n)]Use the result array for prefix products, then traverse backwards with a running suffix product.
Diagram
def product_except_self(nums):
n = len(nums)
result = [1] * n
for i in range(1, n):
result[i] = result[i-1] * nums[i-1]
suffix = 1
for i in range(n-1, -1, -1):
result[i] *= suffix
suffix *= nums[i]
return resultComplexity Comparison
| Approach | Time | Space | Description |
|---|---|---|---|
| Brute Force | O(n^2) | O(1) | For each element, compute the product of all other elements. |
| Prefix and Suffix Products | O(n) | O(n) | Compute prefix products and suffix products, then multiply them. |
| Single Pass with Output Array | O(n) | O(1) | Use the result array for prefix products, then traverse backwards with a running suffix product. |
For each element, compute the product of all other elements.
Compute prefix products and suffix products, then multiply them.
Use the result array for prefix products, then traverse backwards with a running suffix product.
Common Mistakes
Using division which fails when there are zeros in the array
Not handling negative numbers correctly
Off-by-one errors when computing prefix/suffix products