Python coding

Product of all the others

Given a list of integers nums with at least two values, return a list out of the same length where out[i] is the product of every value in nums except the one at index i.

Don't use division: it breaks as soon as a value is 0. Values may be negative or zero. Aim for O(n) time and no extra list besides the output.

Besides the tests, one large input (3,500 numbers) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • products_except_self([2,3,4,5]) → [60,40,30,24]
  • products_except_self([-1,2,0,3]) → [0,0,-6,0]
  • products_except_self([0,4,0,2]) → [0,0,0,0]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

out[i] splits into two parts: the product of everything before i and the product of everything after it. Both are running products, like a prefix sum with *.

Hint 2

Go left to right writing the running product into out[i] before multiplying in nums[i]; then go right to left multiplying out[i] by a running suffix product.

Hint 3

Dividing the total by nums[i] fails on a zero, and two zeros make every answer 0. The two passes need no special case.

Solution and why it works
pythonO(n) · O(1) besides the output
def products_except_self(nums: list[int]) -> list[int]:
    n = len(nums)
    out = [1] * n
    left = 1
    for i in range(n):                   # out[i] = product of everything left of i
        out[i] = left
        left *= nums[i]
    right = 1
    for i in range(n - 1, -1, -1):       # times the product of everything right of i
        out[i] *= right
        right *= nums[i]
    return out

Each answer is the product of the prefix before i times the product of the suffix after it. One left-to-right pass stores the prefix product in out[i] before multiplying nums[i] in; one right-to-left pass multiplies in the suffix product the same way. That is two O(n) passes instead of one O(n) product per index. It never divides, so zeros need no special case; the divide-the-total trick crashes on one zero and needs zero counting to be correct.