1Question
You are given an array of numbers nums. Return a new array answer where answer[i] is the product of all the numbers in nums except nums[i].
You must write an algorithm that runs in O(n) time and without using division. Every product fits in a 32-bit integer.
For index 0 we multiply the others: 2 × 3 × 4 = 24. For index 3: 1 × 2 × 3 = 6.
The 0 is in every product except its own. So all other answers are 0, and the answer for the 0 is (−1) × 1 × (−3) × 3 = 9.
Each position gets the other number.
Constraints
Up to 100,000 numbers. Multiplying all the others for each position is about 10 billion steps. That is too slow, so we need O(n).
Values are small, and can be negative or zero. A zero changes how the answer looks, so we must handle it.
The easy idea “multiply everything, then divide by nums[i]” is not allowed. It also breaks when a number is 0.
Can you use only O(1) extra space? The output array does not count as extra space. Yes: reuse it.
2Hints
Open one hint at a time. Try to think before you open the next one.
3Pattern
Prefix and Suffix Products
Combine what is on the left with what is on the right, using two running products.
Every answer is made of two parts that never include nums[i]: the product of the left side and the product of the right side. A running product gives us each side in one pass:
Pass 1 (left to right) stores the left part. Pass 2 (right to left) multiplies in the right part. Division is never needed.
How to spot this pattern
- For each position you need “everything except this one”.
- The operation can be combined step by step (multiply, add, max, min).
- You are not allowed to “undo” the operation, for example no division.
- The same left or right work would be repeated for many positions.
4Explanation
The big idea: Make the output array in two passes. We keep one running number each time.
Keep prefix, starting at 1. At each i, set answer[i] = prefix, then prefix *= nums[i].
Keep suffix, starting at 1. At each i, do answer[i] *= suffix, then suffix *= nums[i].
Why save before multiplying? We want the product of the numbers before position i. If we multiplied nums[i] in first, the position would count itself.
Why does it work? After pass 1, answer[i] holds the left product. In pass 2 we multiply by the right product. Left × right is everything except nums[i].
5Brute Force
For each position, multiply all the other numbers.
Idea
This follows the question word for word. For each position i we:
- Start with
product = 1. - Loop over every position
jand skipj == i. - Multiply the rest, then save the result as
answer[i].
def product_except_self_brute(nums):
n = len(nums)
answer = []
for i in range(n):
product = 1
for j in range(n):
if j != i: # skip the number at position i
product *= nums[j]
answer.append(product)
return answer
print(product_except_self_brute([1, 2, 3, 4])) # [24, 12, 8, 6]6Optimal Solution
Two passes: left products first, then right products.
def product_except_self(nums):
n = len(nums)
answer = [1] * n
prefix = 1 # product of everything to the left
for i in range(n):
answer[i] = prefix # save BEFORE multiplying nums[i]
prefix *= nums[i]
suffix = 1 # product of everything to the right
for i in range(n - 1, -1, -1):
answer[i] *= suffix # combine left and right
suffix *= nums[i]
return answer
print(product_except_self([1, 2, 3, 4])) # [24, 12, 8, 6]7Time and Space Complexity
Let n be the number of items in the array.
Brute force
Optimal (prefix and suffix)
How big is the difference?
Approximate number of multiplications:
| n | Brute force (n²) | Two passes (2n) |
|---|---|---|
| 10 | 90 | 20 |
| 1,000 | 999,000 | 2,000 |
| 100,000 | about 10 billion | 200,000 |
For the biggest input in this problem, the two-pass method does around 50,000 times less work.