codejump
MediumPythonJavaScriptTypeScript

Prefix Products — Product of Array Except Self

AlgorithmsPrefix SumArrays

Return an array answer where answer[i] is the product of every element of
nums except nums[i].

Without division: dividing the total product breaks as soon as the array
contains a zero, which is exactly the case interviewers check. Every
answer[i] is (product of everything to the left) × (product of everything to
the right): one pass left-to-right, one pass right-to-left, O(n).

Examples

solve([1, 2, 3, 4])        → [24, 12, 8, 6]
solve([-1, 1, 0, -3, 3])   → [0, 0, 9, 0, 0]
solve([2, 3])              → [3, 2]

Constraints

  • 2 <= nums.length <= 100000
  • Every product fits in a safe integer.
  • A product equal to zero is returned as 0 (never -0).

Sample tests

Test #1The classic example
Input: [[1,2,3,4]]
Output: [24,12,8,6]
Test #2One zero
Input: [[-1,1,0,-3,3]]
Output: [0,0,9,0,0]
Test #3Two elements swap
Input: [[2,3]]
Output: [3,2]