For every input position, multiply all the other values without using division.
Problem
Input. An integer list nums, possibly containing zeros, negatives, and repeated values.
Output. Return an equally long list whose entry i is the product of all input values except nums[i].
Rules. Exclude only the current occurrence, not every occurrence with the same value.
Do not use division or mutate the input. Zeros must be handled correctly.
Empty input returns []; a singleton returns [1], using the empty-product convention.
Example. [1, 2, 3, 4] returns [24, 12, 8, 6].
For [0, 2, 3], return [6, 0, 0]; with two zeros every output is zero.
Picture: Two Exclusive Sides
Problem trace
Separate zero-input case: exclude the current value, not every zero
Reference drawing
Problem trace
Write the other-side product before incorporating the current value
Execution trace
- prefix i
- 0
- phase
- left to right
- prefix
- 1
- operation
- ready to write out[0]→out[0] = 1; prefix = 1 * 1 = 1
- phase
- left to right→not shown
- prefix i
- 0→1
- prefix
- 1→2
- operation
- out[0] = 1; prefix = 1 * 1 = 1→out[1] = 1; prefix = 1 * 2 = 2
- prefix i
- 1→2
- prefix
- 2→6
- operation
- out[1] = 1; prefix = 1 * 2 = 2→out[2] = 2; prefix = 2 * 3 = 6
- prefix i
- 2→3
- prefix
- 6→24
- operation
- out[2] = 2; prefix = 2 * 3 = 6→out[3] = 6; prefix = 6 * 4 = 24
- suffix
- not shown→4
- operation
- out[3] = 6; prefix = 6 * 4 = 24→out[3] = 6 * 1 = 6; suffix = 1 * 4 = 4
- prefix
- 24→not shown
- suffix i
- 3→2
- suffix
- 4→12
- operation
- out[3] = 6 * 1 = 6; suffix = 1 * 4 = 4→out[2] = 2 * 4 = 8; suffix = 4 * 3 = 12
- suffix i
- 2→1
- suffix
- 12→24
- operation
- out[2] = 2 * 4 = 8; suffix = 4 * 3 = 12→out[1] = 1 * 12 = 12; suffix = 12 * 2 = 24
- suffix i
- 1→0
- operation
- out[1] = 1 * 12 = 12; suffix = 12 * 2 = 24→out[0] = 1 * 24 = 24; suffix = 24 * 1 = 24
- result
- not shown→[24, 12, 8, 6]
- Recognize it
- Each output excludes exactly one array position, division is forbidden, and multiplication can be accumulated from either boundary.
- Keep true
- Before prefix index i, prefix is the product of nums[0..i-1]. Before suffix index i, suffix is the product of nums[i+1..n-1], while out[i] already stores the left product.
- Reuse it
- When every answer excludes one position and the operation is associative, save the contribution from one side and sweep the other side with a scalar; the same decomposition works for left/right minima, maxima, and cumulative constraints.
The figure’s out is the code’s answer; i is index.
The first pass writes [1, 1, 2, 6]. The reverse pass uses suffix values 1, 4, 12, 24, in that order.
| Index | Strictly before | Strictly after | Combined output |
|---|---|---|---|
| 0 | 1 | 24 | 24 |
| 1 | 1 | 12 | 12 |
| 2 | 2 | 4 | 8 |
| 3 | 6 | 1 | 6 |
Before a forward write, prefix includes exactly positions below index. Only after writing may it consume num.
The reverse loop similarly combines the current exclusive suffix before consuming nums[index].
Identity 1 represents an empty side. Every other position appears exactly once; the current position never appears.
Code
def product_except_self(nums: list[int]) -> list[int]:
answer = [1] * len(nums)
prefix = 1
for index, num in enumerate(nums):
answer[index] = prefix
prefix *= num
suffix = 1
for index in range(len(nums) - 1, -1, -1):
answer[index] *= suffix
suffix *= nums[index]
return answer
Cost: arithmetic operations and constant accumulator slots beyond the output. Unbounded integer multiplication has nonconstant bit cost.
| Input | Output | Check |
|---|---|---|
[0, 2, 3] | [6, 0, 0] | Only the zero position excludes that zero |
[0, 0, 3] | [0, 0, 0] | Every exclusion still contains a zero |
[-1, 2, 3] | [6, -3, -2] | Signs follow the remaining factors |
Change 1: Products Modulo a Positive Integer
New task. Return each excluded product modulo modulus > 0.
Picture and change. Reduce accumulators and outputs after multiplication; keep the exclusive order. No modular inverse is needed.
Code.
def product_except_mod(nums, modulus):
answer = [1 % modulus] * len(nums)
prefix = 1 % modulus
for index, value in enumerate(nums):
answer[index] = prefix
prefix = prefix * value % modulus
suffix = 1 % modulus
for index in range(len(nums) - 1, -1, -1):
answer[index] = answer[index] * suffix % modulus
suffix = suffix * nums[index] % modulus
return answer
Check. [2, 3, 4] modulo 5 gives [2, 3, 1]; [0, 2, 3] modulo 6 gives all zeros.
Use when. The contract requires modular results, including composite moduli.
Change 2: Sum Every Other Value
New task. Replace multiplication with integer addition.
Picture and change. Addition has identity 0 and a safe subtraction inverse. One total now suffices.
Code.
def sum_except_self(nums):
total = sum(nums)
return [total - value for value in nums]
Check. [1, 2, 3, 4] gives [9, 8, 7, 6]; [0] gives [0].
Use when. The changed operator permits safe removal of the current contribution.
Failure: Consuming Before Writing
For [2, 3], updating prefix first gives inclusive products [2, 6], not required exclusive products [1, 2].
Transfer Check
For ordered string concatenation, which reverse update preserves order?
Reasoned Answer
Use suffix = value + suffix, with identity "". Appending to the suffix would reverse the right-hand sequence.
What Can Transfer to Another Operator?
Associativity permits regrouping operations without changing the result.
The operator also needs an identity for empty sides, and both scans must preserve the original element order.
Multiplication hides this order constraint because it is commutative.
For strings ['a', 'b', 'c'], excluding the middle must produce 'ac', while the first output must be 'bc', not 'cb'.
The original implementation does not divide, so zero factors need no special branch. Dividing the total product by the current value would fail at zero and is forbidden by the original task. Integer subtraction in the sum variant is a changed contract, not permission to divide products.
Constant accumulator count does not mean constant bytes for arbitrarily large integers. All implementations allocate an output proportional to input length; the required output is not auxiliary workspace. The modular variant requires a positive integer modulus; modulus 1 correctly produces zero residues, even for a singleton.