Skip to content
Problem · Canonical Warm-Up
mediumprefix · suffix · no-divisionTime · O(n)Space · O(1) extra

Product of Array Except Self

Problem statement

Statement

Given an integer array nums, return an array answer where answer[i] is the product of every element of nums except nums[i]. You must run in O(n) time and you may not use division.

Examples

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

nums = [-1, 1, 0, -3, 3]
-> [0, 0, 9, 0, 0]   (only the slot holding the zero survives)

nums = [0, 0]
-> [0, 0]            (two zeros kill every position)

nums = [2, 3]
-> [3, 2]

Constraints

  • 2 <= len(nums) <= 10^5
  • -30 <= nums[i] <= 30
  • Every prefix and suffix product fits in a 32-bit signed integer, so you never need big integers.
  • The output array is conventionally excluded from the space bound.

What this problem is really testing

The no-division rule is not arbitrary difficulty for its own sake. Division looks like a one-liner (compute the total product, divide by each element) and it is wrong twice over. It breaks on any zero, and with two zeros it cannot be patched by special-casing, because every output is zero and the surviving total is meaningless. Forbidding division forces you to find the structure that was hiding behind the arithmetic shortcut.

That structure is a split. The product of everything except nums[i] is the product of everything to its left times the product of everything to its right. Once stated that way, the problem is no longer about products at all: it is about computing, for every position, an aggregate of the prefix before it and the suffix after it. The same skeleton computes running sums, running maxima, running counts of any associative operation. Recognising the shape is worth more than the specific answer, and it is the shape explored in prefix sums in practice.

The elegant part is the memory. The obvious implementation builds a left array and a right array, then multiplies them pairwise, which is three arrays and O(n) auxiliary space. The trick is to notice that the two passes touch each index at different times, so the output array can hold the left products during the first pass and absorb the right products during the second, with a single scalar carrying the running suffix. Two passes, one array, one variable. That collapse from three arrays to one is precisely what the interviewer is waiting to see.