QuestionsDSA

Product of Array Except Self

Prefix SumMediumDSA

Return an array where output[i] is the product of every element except nums[i] — without using division and in O(n). e.g. [1,2,3,4] → [24,12,8,6].

What it tests

Turning a 'combine everything but me' requirement into a prefix pass and a suffix pass.

Approach & answer

The no-division constraint is the whole point (division breaks on a zero anyway). Answer for i is (product of everything left of i) × (product of everything right of i). Do two sweeps: a left-to-right pass filling res[i] with the running prefix product, then a right-to-left pass multiplying in the running suffix product. You can keep the suffix in a single scalar so no second array is needed — O(1) extra space beyond the output. This is the prefix-sum pattern in multiplicative form: precompute cumulative results from both ends so each answer is an O(1) combine. Zeros are handled automatically — one zero makes every other slot's prefix-or-suffix carry it, and the zero slot itself gets the product of all non-zero neighbours.

Use this technique when

Each output combines everything on both sides of i → prefix pass + suffix pass, no division.

Complexity

Time O(n) · Space O(1) extra (output aside)

References

js