Division-Free Array Products Excluding Each Index
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given an integer list nums of length n, construct a list result of the same length where each entry result[i] equals the product of all n - 1 elements at indices j != i.
Your implementation must satisfy three strict rules:
- No division: do not use
/or//anywhere in your code. - Linear runtime: finish in
O(n)time. - Constant extra workspace: use
O(1)auxiliary memory (the returnedresultlist is not counted as extra memory).
def product_except_self(nums: List[int]) -> List[int]:
Examples
Example 1
- Input:
nums = [3, -2, 5, 2] - Output:
[-20, 30, -12, -30] - Explanation:
result[0] = (-2) * 5 * 2 = -20result[1] = 3 * 5 * 2 = 30result[2] = 3 * (-2) * 2 = -12result[3] = 3 * (-2) * 5 = -30
Example 2
- Input:
nums = [4, 0, -2, 3, -5] - Output:
[0, 120, 0, 0, 0] - Explanation: Every slot other than index
1includesnums[1] = 0in its product and becomes0, whereasresult[1]multiplies the remaining four numbers:4 * (-2) * 3 * (-5) = 120.
Constraints
2 <= len(nums) <= 10^5-10 <= nums[i] <= 10for every0 <= i < len(nums)- Every prefix product and every suffix product of
numsfits within a signed 64-bit integer.
Step-by-step walkthrough
Understand the goal and constraints
Given an integer list
numsof lengthn(2 <= n <= 10^5, values in[-10, 10]), we must build a listresultwhereresult[i]multiplies every entry ofnumsexceptnums[i].Three rules govern the solution:
- No division: multiplying the entire list and dividing by
nums[i]is forbidden (and fails on zeros anyway, such as Example 2[4, 0, -2, 3, -5] -> [0, 120, 0, 0, 0]). O(n)runtime: only a fixed number of linear scans overnumsis allowed.O(1)auxiliary memory: the output listresultdoes not count as extra space, so beyondresultwe may only allocate scalar variables — noO(n)scratch lists.
- No division: multiplying the entire list and dividing by
Why multiplying from scratch at each index is too slow
Looping over every index
iand multiplying alln - 1other elements performsn * (n - 1) ≈ 10^10multiplications atn = 10^5.Writing out the desired products for
nums = [a, b, c, d, e]shows why that nested loop repeats work:result[0] = b * c * d * e result[1] = a * c * d * e result[2] = a * b * d * e result[3] = a * b * c * e result[4] = a * b * c * dAdjacent rows share almost identical left and right sub-products.
Key insight: split into left prefix and right suffix products
Every row splits around index
iinto everything strictly beforeimultiplied by everything strictly afteri:index: 0 1 ... i - 1 i i + 1 ... n - 1 nums: [n_0, n_1, ..., n_{i-1}, n_i, n_{i+1}, ..., n_{n-1}] \___________________________/ ^ \_____________________/ left prefix product skip! right suffix product- At
i = 0, nothing sits to the left, so the empty product is1(the multiplicative identity). - At
i = n - 1, nothing sits to the right, so the right suffix product also starts at1. - Stepping right updates
prefix_product *= nums[i]inO(1)time, and stepping left updatessuffix_product *= nums[i]inO(1)time. - Zeros work automatically: if
nums[1] == 0,0enters every prefix fori > 1and every suffix fori < 1, while index1itself multiplies onlynums[0]andnums[2..n-1].
- At
Eliminate extra arrays to achieve O(1) auxiliary space
Storing separate
leftandrightlists would consumeO(n)extra memory. Instead, we useresultitself across two passes:- Pass 1 (
0ton - 1): carryprefix_productin a single integer and store it inresult[i]. - Pass 2 (
n - 1down to0): carrysuffix_productin a single integer and multiplyresult[i] *= suffix_product.
Notice the statement order inside each loop: update
result[i]before multiplyingnums[i]into the running accumulator sonums[i]never enters its own slot.def product_except_self(nums: List[int]) -> List[int]: n = len(nums) # result[i] starts as the left prefix product and becomes prefix * suffix in pass 2. result = [1] * n # Pass 1 (left to right): prefix_product holds nums[0] * ... * nums[i - 1] (1 when i == 0). prefix_product = 1 for i in range(n): # Store before multiplying by nums[i] so nums[i] is excluded from its own answer. result[i] = prefix_product prefix_product *= nums[i] # Pass 2 (right to left): suffix_product holds nums[i + 1] * ... * nums[n - 1] in O(1) space. suffix_product = 1 for i in range(n - 1, -1, -1): # Multiply the stored left prefix by everything strictly to the right of index i. result[i] *= suffix_product suffix_product *= nums[i] return result- Pass 1 (
Trace Example 1 and Example 2 step by step
Example 1:
nums = [3, -2, 5, 2]Pass 1 (forward): i = 0: result[0] = 1, then prefix_product = 1 * 3 = 3 i = 1: result[1] = 3, then prefix_product = 3 * -2 = -6 i = 2: result[2] = -6, then prefix_product = -6 * 5 = -30 i = 3: result[3] = -30, then prefix_product = -30 * 2 = -60 result after Pass 1: [1, 3, -6, -30] Pass 2 (backward): i = 3: result[3] = -30 * 1 = -30, then suffix_product = 1 * 2 = 2 i = 2: result[2] = -6 * 2 = -12, then suffix_product = 2 * 5 = 10 i = 1: result[1] = 3 * 10 = 30, then suffix_product = 10 * -2 = -20 i = 0: result[0] = 1 * -20 = -20, then suffix_product = -20 * 3 = -60 final result: [-20, 30, -12, -30]Example 2:
nums = [4, 0, -2, 3, -5]Pass 1 (forward): result = [1, 4, 0, 0, 0] (0 enters prefix_product after i = 1) Pass 2 (backward): i = 4: result[4] = 0 * 1 = 0, suffix_product -> -5 i = 3: result[3] = 0 * -5 = 0, suffix_product -> -15 i = 2: result[2] = 0 * -15 = 0, suffix_product -> 30 i = 1: result[1] = 4 * 30 = 120, suffix_product -> 0 (0 enters suffix_product after i = 1) i = 0: result[0] = 1 * 0 = 0, suffix_product -> 0 final result: [0, 120, 0, 0, 0]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def product_except_self(nums: List[int]) -> List[int]: n = len(nums) # result[i] starts as the left prefix product and becomes prefix * suffix in pass 2. result = [1] * n # Pass 1 (left to right): prefix_product holds nums[0] * ... * nums[i - 1] (1 when i == 0). prefix_product = 1 for i in range(n): # Store before multiplying by nums[i] so nums[i] is excluded from its own answer. result[i] = prefix_product prefix_product *= nums[i] # Pass 2 (right to left): suffix_product holds nums[i + 1] * ... * nums[n - 1] in O(1) space. suffix_product = 1 for i in range(n - 1, -1, -1): # Multiply the stored left prefix by everything strictly to the right of index i. result[i] *= suffix_product suffix_product *= nums[i] return result✅ Submit now — all tests should pass.
Intuition & how it works
Picture people standing in a row, each holding a numbered card, where every person wants the product of everyone else's cards without dividing. Pass a notepad from left to right: each person first copies down the running product written on the pad (everyone to their left), then multiplies their own card onto the pad before passing it along. Next, pass a second pad from right to left in the exact same way; multiplying each person's left total by their right total gives the product of everyone except themselves.
Multiplying n - 1 elements from scratch at every index takes O(n^2) time (~10^10 multiplications for n = 10^5). Meanwhile, multiplying the entire array once and dividing by nums[i] breaks the no-division constraint and collapses whenever any entry is 0 (division by 0 raises an error, and a single 0 wipes out the grand product needed at that zero's own index).
Instead, we combine a prefix product (the product of all entries strictly to the left of index i) and a suffix product (the product of all entries strictly to the right of index i). To stay within O(1) auxiliary space (extra memory beyond the input and the returned output list), Pass 1 writes each prefix product straight into result[i], and Pass 2 carries one scalar suffix_product from right to left, multiplying it into result[i].
Trace nums = [3, -2, 5, 2]:
1. Forward pass (prefix_product starts at 1): writes [1, 3, -6, -30] into result.
2. Backward pass (suffix_product starts at 1):
- i = 3: result[3] = -30 * 1 = -30, then suffix_product becomes 1 * 2 = 2.
- i = 2: result[2] = -6 * 2 = -12, then suffix_product becomes 2 * 5 = 10.
- i = 1: result[1] = 3 * 10 = 30, then suffix_product becomes 10 * (-2) = -20.
- i = 0: result[0] = 1 * (-20) = -20, yielding [-20, 30, -12, -30].
Complexity
- Time:
O(n), wheren = len(nums). We sweep acrossnumsonce forward and once backward, doing constant-time integer arithmetic per slot. - Space:
O(1)auxiliary space. Excluding the returnedO(n)listresult, only scalar variables (n,prefix_product,suffix_product,i) are allocated.
Edge cases
- Single zero (
[4, 0, -2, 3, -5]): every index except1picks up0from either its prefix or suffix, while index1computes4 * (-2) * 3 * (-5) = 120. - Multiple zeros (
[0, 2, 0, 3]): every index has at least one0on its left or right, returning[0, 0, 0, 0]with zero special-case branches. - Zero at index
0orn - 1([0, -7]): index0multipliesprefix_product = 1bysuffix_product = -7to get-7, while index1gets0 * 1 = 0. - Negative signs (
[-1, -2, -3]): signs alternate naturally during multiplication, producing[6, 3, 2]. - Minimum size
n = 2([-2, 5]): swaps the pair into[5, -2]. - 64-bit integer width in statically typed languages: Python
intnever overflows, whereas in C++/Java[10]*18 + [0] + [10]*18has every prefix and suffix<= 10^18yet produces10^36at index18— a good boundary detail to mention in interviews.
Common mistakes
- Updating the running product before writing
result[i]: multiplyingprefix_product *= nums[i]first accidentally includesnums[i]inresult[i]. - Starting
prefix_productorsuffix_productat0:1is the multiplicative identity; starting at0fills the entire output with zeros. - Allocating separate
leftandrightlists of sizen: works inO(n)time, but violates theO(1)auxiliary space rule. - Using floating-point division or
math.log: violates the division ban, breaks on zeros and negatives, and loses integer precision.
Alternative approaches
- Two helper lists (
left[i]andright[i]): build both lists explicitly and multiply element-wise. Useful to explain the core idea first before optimizing space down toO(1). - Zero-counting + integer division (when division is allowed): count zeros and multiply non-zero entries in one scan; output all
0s whenzeros >= 2, placenonzero_prodsolely at the zero's slot whenzeros == 1, or return[nonzero_prod // x for x in nums]whenzeros == 0.
Follow-up questions
- How does the two-pass algorithm behave when two or more entries in
numsare zero? It returns all zeros with no extraifchecks. If zeros appear at positionsaandb(a < b),prefix_productbecomes0for every indexi > a(coveringb), whilesuffix_productbecomes0for every indexi < b(coveringa), so every entry inresultis multiplied by0. - If you had to overwrite
numsin place so that even the output list could not be allocated separately (O(1)total extra memory), is that achievable with or without division? With division allowed, yes: scan once to count zeros and multiply non-zero values, then overwritenums[i]in a second scan using the zero-count cases. Without division, overwritingnums[i]withprefix_productduring Pass 1 destroys the originalnums[i]needed to advancesuffix_productin Pass 2 — unless you bit-pack the tiny original value (-10..10takes 5 bits) alongside the prefix product inside a wider integer word. - Suppose you instead needed the product of every contiguous window of length
kacrossnumswithout using division — how would you compute all windows inO(n)time? Partitionnumsinto contiguous blocks of lengthk(0..k-1,k..2k-1, ...) and precomputeblock_prefix[i](product fromi's block start throughi) andblock_suffix[i](product fromithroughi's block end). Every length-kwindow[i .. i + k - 1]either aligns with a block (i % k == 0, answerblock_suffix[i]) or straddles two neighboring blocks (answerblock_suffix[i] * block_prefix[i + k - 1]), takingO(1)per window with zero divisions and full zero safety.
Follow-up questions
- How does the two-pass algorithm behave when two or more entries in `nums` are zero?
- If you had to overwrite `nums` in place so that even the output list could not be allocated separately (`O(1)` total extra memory), is that achievable with or without division?
- Suppose you instead needed the product of every contiguous window of length `k` across `nums` without using division — how would you compute all windows in `O(n)` time?
Similar questions
- Highest-Sum Path in an Array-Backed Binary Tree
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One