Product of Array Except Self solution explained

Product of Array Except Self is solved without division by multiplying two running products: everything to the left of each position and everything to the right of it. Fill the output with left products in one pass, then sweep back from the end with a running right product, for O(n) time and O(1) extra space beyond the output.

By Published 8 min read

The problem, in our words

You are handed an array of integers. Produce a second array of the same length in which position i contains the result of multiplying together every input value except the one at position i. The usual version adds two conditions: do not use division, and finish in linear time. The array has at least two entries in most tellings, but ask, because one entry raises the question of what an empty product should be.

Arrays invented for this walkthrough
InputOutputCheck
[2, 5, 3][15, 6, 10]5 × 3, 2 × 3, 2 × 5
[3, -2, 5, -1][10, -15, 6, -30]Signs follow the count of negatives among the other three
[4, 0, 2, 1][0, 8, 0, 0]Only the zero's own slot avoids multiplying by zero
[0, 3, 0][0, 0, 0]Two zeros make every slot zero
Arrays invented for this walkthrough. Scroll sideways on a small screen.

Before you plan, ask whether the product can exceed a 32-bit or 64-bit integer, whether division is really off the table, and whether the output array counts toward the space limit. That last question matters, since the best answer uses only the output array plus one variable.

Most candidates see the division trick within seconds, which is exactly why the problem forbids it. The real test is whether you can split a quantity that depends on everything except one position into two pieces you can build incrementally: the part before and the part after. That split is the prefix-sum idea moved from addition to multiplication. Interviewers also like the zero cases, because a candidate who reaches for division has to explain them precisely.

Where the conversation goes next

  • Constant extra space. Store the left products directly in the output, then multiply in the right products with a single running variable on the way back.
  • What if division is allowed? Count the zeros. With none, divide the total product by each value. With exactly one, only the zero's slot is non-zero and equals the product of the rest. With two or more, everything is zero.
  • Overflow. Products grow very fast. Ask about value bounds, use a 64-bit type, or return results modulo a prime if the interviewer asks for it, in which case division would need a modular inverse.
  • Many range queries. Precompute prefix products once so the product of any slice is two lookups, as long as there are no zeros; with zeros, also keep a prefix count of zeros.
  • Sums instead of products. The same two-sided idea answers "sum of everything except me" trivially as total minus value, which is a nice contrast to explain why products are harder.

Brute force: multiply the others for every slot

For each index i, start a running product at 1 and multiply every value whose index is not i. That is n - 1 multiplications per slot and n slots, so O(n²) time with no memory beyond the output. It is clearly correct, handles zeros without any special code, and makes a perfect reference to test against.

def others_product_slow(values):
    out = []
    for i in range(len(values)):
        prod = 1
        for j, v in enumerate(values):
            if j != i:
                prod *= v
        out.append(prod)
    return out
Brute force, O(n²) time.

Optimal approach: left products times right products

Write the answer for slot i as two factors. The first is the product of all values before i, and the second is the product of all values after i. Both factors can be built cheaply: the product before i is the product before i - 1, times the value at i - 1. So one forward pass fills the before-products, and one backward pass supplies the after-products.

To keep extra memory constant, let the output array hold the before-products after the first pass. On the way back, keep a single variable with the product of everything to the right of the current index, multiply it into the output slot, and then fold the current value into it. Zeros need no special handling, because a zero simply makes every factor that contains it zero, which is the correct answer.

def others_product(values):
    n = len(values)
    out = [1] * n
    left = 1
    for i in range(n):
        out[i] = left        # product of everything before i
        left *= values[i]
    right = 1
    for i in range(n - 1, -1, -1):
        out[i] *= right      # times product of everything after i
        right *= values[i]
    return out
Python: two passes, O(n) time and O(1) extra space beyond the output.
#include <vector>

std::vector<long long> othersProduct(const std::vector<long long>& values) {
    const std::size_t n = values.size();
    std::vector<long long> out(n, 1);
    long long left = 1;
    for (std::size_t i = 0; i < n; ++i) {
        out[i] = left;
        left *= values[i];
    }
    long long right = 1;
    for (std::size_t i = n; i-- > 0;) {
        out[i] *= right;
        right *= values[i];
    }
    return out;
}
C++17: the same two sweeps with 64-bit products. Ask about bounds before trusting any fixed-width type.

The backward loop in C++ uses the i-- > 0 form so that an unsigned index never wraps below zero. A signed int index with i >= 0 works too; just do not mix an unsigned type with that condition, or the loop never ends.

def others_product_by_division(values):
    zeros = values.count(0)
    if zeros >= 2:
        return [0] * len(values)
    total = 1
    for v in values:
        if v != 0:
            total *= v
    if zeros == 1:
        return [total if v == 0 else 0 for v in values]
    return [total // v for v in values]
Follow-up when division is allowed: count zeros first, then divide.

Integer division is exact here because each value divides the product it is part of. In a language with floating-point numbers only, prefer the two-pass version, since division can introduce rounding.

Complexity table

Time and extra memory, not counting the output array
ApproachTimeExtra spaceCaveat
Multiply the others for each slotO(n²)O(1)Too slow past a few thousand entries
Total product divided by each valueO(n)O(1)Needs zero counting, often disallowed
Separate left and right arraysO(n)O(n)Clear first version to write
Left products in the output, running right productO(n)O(1)The expected final answer
Time and extra memory, not counting the output array. Scroll sideways on a small screen.

Edge cases

  • No zeros: every slot is a genuine product of the other values.
  • Exactly one zero: only the zero's slot is non-zero.
  • Two or more zeros: every slot is zero.
  • Negative numbers: the sign of each slot depends on how many negatives remain once that slot is removed.
  • Two entries: each slot is simply the other value, a good one-line trace.
  • Large magnitudes: decide on 64-bit integers, big integers or a modulus before you write the loop.

Frequent slips

  • Using division after being told not to, or using it and then forgetting the zero cases.
  • Including the value at i in its own left or right product because the update and the write happen in the wrong order.
  • Calling the two-array version O(1) space.
  • Starting the running products at 0 instead of 1.
  • An unsigned loop counter in C++ that is compared with >= 0 on the backward pass.

How to explain it out loud

Fictional example

Explaining the two passes clearly
Candidate
Each slot needs the product of everything except itself, which splits into the product to its left times the product to its right.
Candidate
On the way forward I write the left product into the output and then multiply in the current value. On the way back I keep a running right product, multiply it into each slot, then fold in that slot's value.
Candidate
Two linear passes, and only one extra variable besides the output. For 2, 5, 3 the first pass writes 1, 2, 10, and the second multiplies by 15, 3 and 1 to give 15, 6, 10.

Similar problems to try next

Running values carried through a loop also solve Best Time to Buy and Sell Stock, which keeps a running minimum, and Maximum Subarray, which keeps a running best sum; the product version of that problem even tracks a running minimum and maximum product side by side. Scanning from both ends shows up again in Container With Most Water. Everything else is on the coding problems hub.

Practicing this with Natively

Natively works on Mac and Windows. While you practice, it can read an array problem like this from a screenshot, suggest the before-and-after split along with code, and flag the zero cases you should test. Pair that with a recorded mock round, which it transcribes on your computer, and you can review whether your explanation of the second pass made sense to a listener. See the AI interview assistant.

Questions people ask

How do you solve Product of Array Except Self without division?

Split each answer into the product of the values to its left and the product of the values to its right. A forward pass writes the left products into the output, and a backward pass multiplies in a running right product.

What is the space complexity of the optimal solution?

O(1) extra space if the output array is not counted, because the left products live in the output and the right product is one variable. A version with separate left and right arrays uses O(n).

How does the solution handle zeros?

The two-pass method needs no special case: any prefix or suffix that contains a zero becomes zero. With division you must count zeros, since one zero leaves only its own slot non-zero and two or more zero everything.

Why is division not allowed in this problem?

Division makes the task a one-liner and fails on zeros. Banning it pushes you toward prefix and suffix products, the idea the problem is meant to test.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP