Problem overview
The method productExceptSelf receives a list of integers, nums, and returns a list answer of the same length. Each answer[i] is the product of every element of nums except nums[i]. Division is not allowed, and the method must run in O(n) time with O(1) extra space, not counting the returned list.
For nums = [1, 2, 3, 4] the answer is [24, 12, 8, 6]: the first entry is 2 * 3 * 4, the second is 1 * 3 * 4, and so on. For [-1, 1, 0, -3, 3] the answer is [0, 0, 9, 0, 0]. Every product that includes the zero is zero, and only the entry at the zero's own index leaves it out.
Approach: left products times right products
The obvious plan multiplies everything and divides by nums[i]. Besides being forbidden, it breaks as soon as the list contains a zero, because dividing by zero is an error. The brute-force alternative multiplies the other n - 1 elements for every index, which is O(n²).
The way out is to split each product in two. The product of everything except nums[i] is the product of everything to its left times the product of everything to its right. Both sides can be built with running products, like a running sum, in one pass each:
- Going left to right, store in
answer[i]the product of the elements before indexi(prefix products). - Going right to left, keep one variable,
suffix, with the product of the elements after indexi, and multiply it intoanswer[i].
The right-hand products need no second list, because each one is used exactly once, at the moment the backward pass reaches its index. That is what keeps the extra space at O(1): the output list is reused as the storage for the left products.
On [1, 2, 3, 4] the forward pass leaves answer = [1, 1, 2, 6]. These are the products of nothing, of 1, of 1 * 2 and of 1 * 2 * 3. The backward pass then goes like this:
| i | answer after answer[i] *= suffix | suffix afterwards |
|---|---|---|
| 3 | [1, 1, 2, 6] | 4 |
| 2 | [1, 1, 8, 6] | 12 |
| 1 | [1, 12, 8, 6] | 24 |
| 0 | [24, 12, 8, 6] | 24 |
Step by step
- Store the length in
n, since both loops need it. - Create
answeras[0] * nand setanswer[0]to 1. Nothing lies to the left of the first element, and a product of no numbers is 1, the way an empty sum is 0. - Loop forward with
range(1, n). Index 0 is already filled. - Extend the prefix product:
answer[i]isanswer[i - 1]timesnums[i - 1]. Each entry reuses the one before it. - Start
suffixat 1, for the same reason as the first entry: the last element has nothing to its right. - Loop backward with
range(n - 1, -1, -1). The stop value is left out, so a stop of -1 makes 0 the last index visited, and the step of -1 counts down. - Multiply
answer[i]bysuffix. The entry held the left product; now it holds left times right. - Then multiply
suffixbynums[i], so it covers that element when the loop moves one step left. The order matters: ifsuffixwere updated first,answer[i]would includenums[i]itself. - Return
answer.
The solution in Python
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
answer = [0] * n
answer[0] = 1
for i in range(1, n):
answer[i] = answer[i - 1] * nums[i - 1]
suffix = 1
for i in range(n - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answer
A few Python details are worth knowing:
[0] * nbuilds a list ofnzeros. For numbers this is safe, because integers are immutable and assigning to one slot replaces that slot only.range(n - 1, -1, -1)is the usual way to count down over every index.range(n - 1, 0, -1)would stop one index too early and leaveanswer[0]without its right-hand product.*=updates a list slot in place:answer[i] *= suffixmeansanswer[i] = answer[i] * suffix.- Big numbers are not a problem. Python integers grow as needed, so there is no overflow to guard against. The lesson's constraints keep every product within 32 bits anyway.
Complexity
Time: O(n). The method makes one forward pass and one backward pass, and each step does a single multiplication.
Space: O(1) extra. The only additions beyond the returned list are n, i and suffix. The prefix products live in answer itself.
Edge cases and common mistakes
- Zeros. One zero makes every entry zero except the one at the zero's index:
[5, 0, 2]gives[0, 10, 0]. Two zeros make everything zero:[0, 0, 3]gives[0, 0, 0]. The two-pass method needs no special case, which a division-based approach would. - Two elements.
[2, 3]gives[3, 2]: each answer is the other element. - Negative numbers. They need no special handling.
[-1, 1, 0, -3, 3]gives[0, 0, 9, 0, 0], with the two negative factors in the 9 cancelling out. - Updating
suffixtoo early. Swapping the last two lines of the second loop putsnums[i]into its own answer. - Starting a product at 0. Both
answer[0]andsuffixmust start at 1. Starting at 0 turns every product into 0.
Testing
[1, 2, 3, 4]gives[24, 12, 8, 6].[-1, 1, 0, -3, 3]gives[0, 0, 9, 0, 0].[2, 3]gives[3, 2].[5, 0, 2]gives[0, 10, 0].[0, 0]gives[0, 0].
