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
- Fill the output with prefix products from the left:
out[i]= product ofnums[0..i-1]. - Walk from the right with a running suffix product, multiplying it into
out[i]. - 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.