TRT
Sign in
mediumAdvancedLeetCode#prefix products#suffix products

Product of array except self

Return, for each index, the product of all other elements, with prefix and suffix products and no division.

The Runtime Theory Team1 min read
Taught inPrefix sumsPro — members onlyStore the running total at every position once, and the sum of any range becomes one subtraction. Combined with a hash map, prefix sums count subarrays with a given sum, even with negative numbers.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [1, 2, 3, 4]

out[24, 12, 8, 6]

innums = [-1, 1, 0, -3, 3]

out[0, 0, 9, 0, 0]

innums = [2, 3]

out[3, 2]

Return an array where element i is the product of every element except nums[i], in O(n) time without using division.

Before you code

The answer at i is (product of everything before i) × (product of everything after i). Both are prefix products, one from each end.

Hints

  1. Fill the output with prefix products from the left: out[i] = product of nums[0..i-1].
  2. Walk from the right with a running suffix product, multiplying it into out[i].
  3. That uses O(1) space besides the output. Division would fail on zeros anyway.

Production & complexity notes

When solving Product of array except self on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Prefix sums to reinforce the underlying pattern.

What it practices

Prefix operations other than sums, from Prefix sums.

Not started

Sign in to save your learning progress.

Sign in to save