The machine must return an array where answer[i] is the product of everything except nums[i], and the division operator is banned. The insight: the product excluding index i factors cleanly into "product of everything to the left" times "product of everything to the right". Two passes build those prefixes and suffixes — one output array holds the left products first, then a backward pass multiplies in the running right product.
def product_except_self(nums):
n = len(nums)
ans = [1] * n
for i in range(1, n):
ans[i] = ans[i - 1] * nums[i - 1]
right = 1
for i in range(n - 1, -1, -1):
ans[i] *= right
right *= nums[i]
return ansSteps: (1) forward pass fills ans[i] with the prefix product, (2) backward pass multiplies each element by the running suffix product.
Time is O(n), two passes. Space is O(1) beyond the output array, which LeetCode does not count.
Trickiest edge case: zeros. With one zero, every position except the zero's own is 0 — the prefix/suffix approach handles this naturally, no branching needed. With two or more zeros, the entire answer is zeros. There is no division, so zeros never blow up the math.