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]. 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 operation.
- 2 <= nums.length <= 10⁵
- -30 <= nums[i] <= 30
- The product of any prefix or suffix fits in a 32-bit integer
nums = [1,2,3,4][24,12,8,6]nums = [-1,1,0,-3,3][0,0,9,0,0]nums = [0,4,0][0,0,0]Calculating the product of all elements except the current one is like making a "sandwich" for every index. Each result is the product of everything to the left of the index multiplied by everything to its right. The challenge is to do this in linear time without using division.
The most direct way is to iterate through every index and, for each one, loop through the entire array again to multiply all other elements.
res = [1] * n
for i in range(n):
for j in range(n):
if i != j:
res[i] *= nums[j]
return resIf division were allowed, we could find the total product and divide by each number. However, this is forbidden and becomes impossible if the array contains a zero. This forces us to find the "left-side product" and "right-side product" independently for every number.
We can use two extra arrays to pre-calculate the "sandwich" parts for every index.
L, R = [1] * n, [1] * n
for i in range(1, n):
L[i] = nums[i-1] * L[i-1]
for i in range(n-2, -1, -1):
R[i] = nums[i+1] * R[i+1]
res = [L[i] * R[i] for i in range(n)]
return resWe can achieve the same result using only the output array as workspace.
1. Pass 1 (Forward): Fill the output array with the left-side (Prefix) products.
2. Pass 2 (Backward): Walk backwards and multiply those prefix products by a running right-side (Suffix) total.
res = [1] * n
# Pass 1: Left products
left = 1
for i in range(n):
res[i] = left
left *= nums[i]
# Pass 2: Right products
right = 1
for i in range(n-1, -1, -1):
res[i] *= right
right *= nums[i]res with the product of all elements to the left.right suffix product.Product Pre-Computation
DIVISION-FREE
By calculating Left and Right products separately, we avoid dividing by zero—a common pitfall in this problem.
SPACE-SAVER
We reuse the output array for our prefix pass and update it on the suffix pass, achieving O(1) extra space.