Product of Array Except Self (LeetCode 238): Solution and Explanation

Medium
Array
Prefix Sum

Given an integer array, build an output array where each position holds the product of every other element in the input. You must do it in linear time without using division.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force computes each answer from scratch: for position i, multiply every element except nums[i]. That is O(n²). The tempting shortcut is to multiply everything once and divide by nums[i], but the problem forbids division, and division breaks anyway when the array contains a zero.

Look at what the answer for index i actually is. It is the product of everything to the left of i times the product of everything to the right of i. Both of those are running products that can be built incrementally. The product of everything left of i + 1 is just the product left of i multiplied by nums[i], and the same holds from the other side. So two linear sweeps, one from the left and one from the right, give every answer.

The natural way to code that is two helper arrays, prefix and suffix, followed by one multiplication per index. The reference solution goes one step further and saves the extra memory. It writes the prefix products straight into the result array on the forward pass, using a single running variable. On the backward pass it keeps another running variable for the suffix product and multiplies it into each slot. The output array is required anyway, so the only additional storage is two integers.

Approach: Prefix and suffix products in the output array

  1. Create res of length n filled with 1.
  2. Set prefix = 1. Loop i from 0 to n - 1: store res[i] = prefix, then update prefix *= nums[i]. Now res[i] holds the product of all elements to the left of i.
  3. Set postfix = 1. Loop i from n - 1 down to 0: multiply res[i] *= postfix, then update postfix *= nums[i].
  4. After the backward pass, each res[i] equals the left product times the right product.
  5. Return res.

Step-by-step example

nums = [1, 2, 3, 4]
  1. Forward pass: i = 0 stores 1 (prefix becomes 1), i = 1 stores 1 (prefix 2), i = 2 stores 2 (prefix 6), i = 3 stores 6 (prefix 24). res = [1, 1, 2, 6].
  2. Backward pass, i = 3: res[3] = 6 × 1 = 6, postfix becomes 4.
  3. i = 2: res[2] = 2 × 4 = 8, postfix becomes 12.
  4. i = 1: res[1] = 1 × 12 = 12, postfix becomes 24.
  5. i = 0: res[0] = 1 × 24 = 24. Return [24, 12, 8, 6].

Code: Python, Java, C++

1class Solution:
2    def productExceptSelf(self, nums: List[int]) -> List[int]:
3        res = [1] * (len(nums))
4        prefix = 1
5        for i in range(len(nums)):
6            res[i] = prefix
7            prefix *= nums[i]
8        postfix = 1
9        for i in range(len(nums) - 1, -1, -1):
10            res[i] *= postfix
11            postfix *= nums[i]
12        return res

Time and space complexity

Time

O(n)

There are exactly two passes over the array, each doing constant work per element.

Space

O(1) extra

Aside from the output array, which the problem requires and does not count, only the two running variables prefix and postfix are used.

Other approaches

Separate prefix and suffix arrays (time O(n), space O(n))

Build left[i] and right[i] in two arrays, then set res[i] = left[i] * right[i]. It is easier to reason about when learning the idea, but it uses two extra arrays.

Total product with zero handling (time O(n), space O(1) extra)

Multiply all non-zero elements and count zeros, then divide or return zeros as appropriate. It is O(n) but uses division, which the problem disallows, and the zero cases are easy to get wrong.

Common mistakes

  • Updating prefix before writing it into res[i]. That includes nums[i] in its own product, which is exactly what must be excluded.
  • Initializing res with zeros instead of ones. The backward pass multiplies into the existing values, so a zero start wipes everything out.
  • Reaching for division and then special-casing zeros. One zero makes every other answer zero, and two zeros make all answers zero, so the division path has several branches to get right and is forbidden anyway.
  • Worrying about overflow in Java or C++ without reading the constraints. The problem guarantees every prefix and suffix product fits in a 32-bit integer.

Frequently asked questions

How do you solve Product of Array Except Self without division?

Compute, for each index, the product of everything to its left and everything to its right, using one forward pass and one backward pass. Multiplying those two products gives the answer for that index.

How is the space O(1) if we return an array?

By convention the output array does not count as extra space. The algorithm stores the prefix products in that output array and only adds two scalar variables.

What happens when the array contains zeros?

Nothing special is needed. A zero simply makes the running prefix or suffix zero from that point on, which produces the correct zeros in the answer.

Why not just divide the total product by each element?

The problem forbids it, and it fails when an element is zero because you cannot divide by zero. The prefix and suffix method avoids both issues.