Skip to content
mlmentorship

Product of Array Except Self

For each position, return the product of all other values. Do not use division.

Published · 18 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Product of Array Except Self

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

At index i, combine the product strictly before i with the product strictly after i.

Problem trace

Write the other-side product before incorporating the current value

Input and goalFor each position, return the product of all other values. Do not use division.
Initialize the prefix passStart output as four ones and prefix as 1. Write each exclusive product before consuming the current input.
prefix i=0num 1 / out 10num 2 / out 11num 3 / out 12num 4 / out 13
phaseleft to rightprefix1operationready to write out[0]
prefix i
0
phase
left to right
prefix
1

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.
Start output as four ones and prefix as 1. Write each exclusive product before consuming the current input. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must the current value be multiplied into the running product after writing its contribution to output?
Full interview answer 18 min read
Reading depth

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

Worked example: left and right products exclude exactly the current positionFor (2,0,4), prefix and suffix products produce (0,8,0). The middle output is nonzero even though its own input is zero.For the middle output, exclude itsown zero rather than every zeroindex 02index 10index 24excludecurrent8Only the left and right factorscontribute: eight.All outputs: zero, eight, zero
Read it this way: For (2,0,4), prefix and suffix products produce (0,8,0). The middle output is nonzero even though its own input is zero. Why is the output at the zero position nonzero while the other two outputs are zero?
Reference drawing

Problem trace

Write the other-side product before incorporating the current value

Worked example: left and right products exclude exactly the current positionFor (2,0,4), prefix and suffix products produce (0,8,0). The middle output is nonzero even though its own input is zero.For the middle output, exclude itsown zero rather than every zeroindex 02index 10index 24excludecurrent8Only the left and right factorscontribute: eight.All outputs: zero, eight, zero
Execution trace
Input and goalFor each position, return the product of all other values. Do not use division.
Initialize the prefix passStart output as four ones and prefix as 1. Write each exclusive product before consuming the current input.
prefix i=0num 1 / out 10num 2 / out 11num 3 / out 12num 4 / out 13
phaseleft to rightprefix1operationready to write out[0]
prefix i
0
phase
left to right
prefix
1

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.
Start output as four ones and prefix as 1. Write each exclusive product before consuming the current input. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must the current value be multiplied into the running product after writing its contribution to output?
Read it this way: For (2,0,4), prefix and suffix products produce (0,8,0). The middle output is nonzero even though its own input is zero. Why is the output at the zero position nonzero while the other two outputs are zero?

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.

IndexStrictly beforeStrictly afterCombined output
012424
111212
2248
3616

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.

InputOutputCheck
[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.