Example 1
ready- Input
nums = [ 1, 2, 3, 4 ]- Expected
[ 24, 12, 8, 6 ]- Why
- each position receives the product of the other three values
Imagine removing one item from a chain of multipliers. You need the result for every possible removal, but recomputing the whole chain each time gets expensive fast.
Given an integer array nums, return an array out of the same length where out[i]
is the product of every value in nums except nums[i].
A few ground rules:
2 <= nums.length <= 100_000|value| < 2^31.Hints
Everything except nums[i] has two parts: values to the left of i, and values to
the right. Can you compute those two products without division?
Walk left to right with a running product. Before multiplying by nums[i], store
that running product in out[i]; it now represents everything strictly to the left.
Walk right to left with a second running product. Multiply it into out[i], then
update it with nums[i]. The output array can hold the prefix work, so you don't
need a second helper array.
Can you solve it with constant extra space when the returned array doesn't count toward the space budget?
Visible cases
nums = [
1,
2,
3,
4
][
24,
12,
8,
6
]nums = [
2,
0,
4
][
0,
8,
0
]nums = [
-1,
2,
-3,
4
][
-24,
12,
-8,
6
]Interview signal
For each output position i, scan the entire input and multiply every value whose
position isn't i. It follows the definition directly, which makes it a useful oracle.
def product_except_self(nums: list[int]) -> list[int]:
answer: list[int] = []
for skipped in range(len(nums)):
product = 1
for i, value in enumerate(nums):
if i != skipped:
product *= value
answer.append(product)
return answerTime O(n²) — each of n output positions scans n input values. Space O(1)
besides the returned array.
The repeated work is hiding in plain sight. Neighboring output positions reuse almost all the same factors; only the point where "left" becomes "right" moves.
A prefix product is the product of values before a position. On the first pass, store that left-side product directly in the answer array. Then walk backwards with a running suffix product — the product of values after the current position — and multiply it into the stored prefix.
def product_except_self(nums: list[int]) -> list[int]:
answer = [1] * len(nums)
prefix = 1
for i, value in enumerate(nums):
answer[i] = prefix
prefix *= value
suffix = 1
for i in range(len(nums) - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answerAt index i, answer[i] holds the product strictly to its left, while suffix holds
the product strictly to its right. Their product excludes exactly nums[i]. This logic
also handles zeros naturally: one zero leaves only its own position potentially nonzero,
and two zeros force every output to zero.
Time O(n) — one forward pass and one backward pass. Space O(1) beyond the output array; the two running products are the only extra storage.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
[ 24, 12, 8, 6 ]