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:

  1. No division: do not use / or // anywhere in your code.
  2. Linear runtime: finish in O(n) time.
  3. Constant extra workspace: use O(1) auxiliary memory (the returned result list 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 = -20
    • result[1] = 3 * 5 * 2 = 30
    • result[2] = 3 * (-2) * 2 = -12
    • result[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 1 includes nums[1] = 0 in its product and becomes 0, whereas result[1] multiplies the remaining four numbers: 4 * (-2) * 3 * (-5) = 120.

Constraints

  • 2 <= len(nums) <= 10^5
  • -10 <= nums[i] <= 10 for every 0 <= i < len(nums)
  • Every prefix product and every suffix product of nums fits within a signed 64-bit integer.

Step-by-step walkthrough

  1. Understand the goal and constraints

    Given an integer list nums of length n (2 <= n <= 10^5, values in [-10, 10]), we must build a list result where result[i] multiplies every entry of nums except nums[i].

    Three rules govern the solution:

    1. 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]).
    2. O(n) runtime: only a fixed number of linear scans over nums is allowed.
    3. O(1) auxiliary memory: the output list result does not count as extra space, so beyond result we may only allocate scalar variables — no O(n) scratch lists.
  2. Why multiplying from scratch at each index is too slow

    Looping over every index i and multiplying all n - 1 other elements performs n * (n - 1) ≈ 10^10 multiplications at n = 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 * d
    

    Adjacent rows share almost identical left and right sub-products.

  3. Key insight: split into left prefix and right suffix products

    Every row splits around index i into everything strictly before i multiplied by everything strictly after i:

    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 is 1 (the multiplicative identity).
    • At i = n - 1, nothing sits to the right, so the right suffix product also starts at 1.
    • Stepping right updates prefix_product *= nums[i] in O(1) time, and stepping left updates suffix_product *= nums[i] in O(1) time.
    • Zeros work automatically: if nums[1] == 0, 0 enters every prefix for i > 1 and every suffix for i < 1, while index 1 itself multiplies only nums[0] and nums[2..n-1].
  4. Eliminate extra arrays to achieve O(1) auxiliary space

    Storing separate left and right lists would consume O(n) extra memory. Instead, we use result itself across two passes:

    1. Pass 1 (0 to n - 1): carry prefix_product in a single integer and store it in result[i].
    2. Pass 2 (n - 1 down to 0): carry suffix_product in a single integer and multiply result[i] *= suffix_product.

    Notice the statement order inside each loop: update result[i] before multiplying nums[i] into the running accumulator so nums[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
    
  5. 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]
    
  6. 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), where n = len(nums). We sweep across nums once forward and once backward, doing constant-time integer arithmetic per slot.
  • Space: O(1) auxiliary space. Excluding the returned O(n) list result, only scalar variables (n, prefix_product, suffix_product, i) are allocated.

Edge cases

  • Single zero ([4, 0, -2, 3, -5]): every index except 1 picks up 0 from either its prefix or suffix, while index 1 computes 4 * (-2) * 3 * (-5) = 120.
  • Multiple zeros ([0, 2, 0, 3]): every index has at least one 0 on its left or right, returning [0, 0, 0, 0] with zero special-case branches.
  • Zero at index 0 or n - 1 ([0, -7]): index 0 multiplies prefix_product = 1 by suffix_product = -7 to get -7, while index 1 gets 0 * 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 int never overflows, whereas in C++/Java [10]*18 + [0] + [10]*18 has every prefix and suffix <= 10^18 yet produces 10^36 at index 18 — a good boundary detail to mention in interviews.

Common mistakes

  • Updating the running product before writing result[i]: multiplying prefix_product *= nums[i] first accidentally includes nums[i] in result[i].
  • Starting prefix_product or suffix_product at 0: 1 is the multiplicative identity; starting at 0 fills the entire output with zeros.
  • Allocating separate left and right lists of size n: works in O(n) time, but violates the O(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] and right[i]): build both lists explicitly and multiply element-wise. Useful to explain the core idea first before optimizing space down to O(1).
  • Zero-counting + integer division (when division is allowed): count zeros and multiply non-zero entries in one scan; output all 0s when zeros >= 2, place nonzero_prod solely at the zero's slot when zeros == 1, or return [nonzero_prod // x for x in nums] when zeros == 0.

Follow-up questions

  • How does the two-pass algorithm behave when two or more entries in nums are zero? It returns all zeros with no extra if checks. If zeros appear at positions a and b (a < b), prefix_product becomes 0 for every index i > a (covering b), while suffix_product becomes 0 for every index i < b (covering a), so every entry in result is multiplied by 0.
  • 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? With division allowed, yes: scan once to count zeros and multiply non-zero values, then overwrite nums[i] in a second scan using the zero-count cases. Without division, overwriting nums[i] with prefix_product during Pass 1 destroys the original nums[i] needed to advance suffix_product in Pass 2 — unless you bit-pack the tiny original value (-10..10 takes 5 bits) alongside the prefix product inside a wider integer word.
  • 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? Partition nums into contiguous blocks of length k (0..k-1, k..2k-1, ...) and precompute block_prefix[i] (product from i's block start through i) and block_suffix[i] (product from i through i's block end). Every length-k window [i .. i + k - 1] either aligns with a block (i % k == 0, answer block_suffix[i]) or straddles two neighboring blocks (answer block_suffix[i] * block_prefix[i + k - 1]), taking O(1) per window with zero divisions and full zero safety.

Follow-up questions

Similar questions

More Newrelic interview questions

All 2 Newrelic questions →