Skip to content

Product of Array Except Self

MediumLeetCode #238Time O(n)Space O(1)

You get an integer array. Return a new array where entry i is the product of all elements except nums[i]. Do it in O(n) time and without division.

nums = [1, 2, 3, 4] -> [24, 12, 8, 6] (24 = 2 * 3 * 4, 12 = 1 * 3 * 4, ...)

Brute force multiplies everything else for each index: O(n²). Dividing the total product by nums[i] is banned, and it also breaks on zeros.

Look at what “everything except i” really is: the product of everything to the left of i times the product of everything to the right. Both are running products. First pass, left to right: store the running left product in the output array. Second pass, right to left: multiply each slot by a running right product. The output array doubles as the prefix storage, so no extra array is needed.

Show solutionHide solution
def product_except_self(nums: list[int]) -> list[int]:
n = len(nums)
result = [1] * n
prefix = 1 # product of everything left of i
for i in range(n):
result[i] = prefix
prefix *= nums[i]
suffix = 1 # product of everything right of i
for i in range(n - 1, -1, -1):
result[i] *= suffix
suffix *= nums[i]
return result
  • Time: O(n) — two linear passes.
  • Space: O(1) extra — only two scalar variables. The output array is not counted, as the problem allows.
  • Start both running products at 1, not 0. The first element has nothing to its left, so its left product is the empty product, 1. The same goes for the last element’s right side.
  • Update the answer before the running product. Write result[i] = prefix first, then prefix *= nums[i]. Reversing them includes nums[i] in its own answer.
  • Zeros need no special case with this method. The division approach does: one zero makes every other slot 0, two zeros make everything 0.

Find the contiguous subarray with the largest product. The trick: track both the max and min product ending at each position. A negative number can flip the smallest product into the largest.

Find the index where the sum on the left equals the sum on the right. The trick: the same prefix and suffix idea with sums. Keep the total, and the left sum as you go; the right sum is total - left - nums[i].

Range Sum Query - Immutable (LeetCode 303)

Section titled “Range Sum Query - Immutable (LeetCode 303)”

Answer many “sum from i to j” queries fast. The trick: build a prefix-sum array once, then each query is prefix[j + 1] - prefix[i] in O(1).