Product of array except self
Two passes. The first fills each cell with the product of everything to its left; the second walks backwards multiplying by a running product of everything to the right. O(n) time, no division, and the output array is the only extra memory.
Overview
Why not just divide
Multiply everything, then divide by each element. It is O(n), it is the first thing everyone says, and the question explicitly forbids it — because it breaks on zero. One zero makes every other answer a division by zero; two zeros make every answer zero.
You can special-case the zero count, and it works. Say that, then give the prefix/suffix answer, because the point of the question is the decomposition rather than the arithmetic.
Step through it
What to watch
- After the first pass each cell knows only about its left.
- The second pass folds in the right side without a second array.
- No element is ever divided — zeros need no special handling.
Say this out loud
"Prefix products left to right, then a running suffix product right to left, multiplied into the same array. O(n) time, O(1) extra space beyond the output - and no division, so zeros are not a special case."