Return an array where each element is the product of all the others — i.e.
out[i] = product of nums except nums[i] — without using division.
productExceptSelf(nums)
Input format: space-separated integers. Output the result, space-separated.
[1, 2, 3, 4] // → [24, 12, 8, 6]
[2, 3] // → [3, 2]
[5] // → [1]
The natural first instinct: multiply everything, then divide by nums[i]. That works arithmetically, but division is forbidden — and for good reason, since it breaks the moment any element is zero, and multiple zeros make it even messier.
So: how do you compute, for every position, the product of everything except that position, without dividing?
"Everything except position i" is two independent pieces: everything strictly left of i, and everything strictly right. Knowing both products and multiplying them gives exactly what you want, without touching nums[i] itself.
That suggests two auxiliary arrays: a prefix-product array (product of everything before each index) and a suffix-product array (product of everything after). The answer at i is prefix[i] times suffix[i].
Build the output in two sweeps over the same array:
After both passes, out[i] holds prefix times suffix — exactly the product of everything except nums[i].
No division means zeros are handled gracefully. One zero element makes every other position's answer zero (the zero sits in their prefix or suffix product), while the zero's own position ends up as the product of the non-zero elements — computed correctly with no special-casing.
The naive approach — loop through the array skipping one index, for every index — is O(n²), redoing an O(n) scan n times. The prefix/suffix technique carries forward running products instead of recomputing them — two linear sweeps, O(n) total, only the output array as extra memory. "Running total from the left, running total from the right" applies to any "everything except this position" problem.
def product_except_self(nums):
n = len(nums)
out = [1] * n
prefix = 1
for i in range(n):
out[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(n - 1, -1, -1):
out[i] *= suffix
suffix *= nums[i]
return out
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.