intermediate · prefix products · arrays

Every product but your own

Problem

Given an array of integers, produce a new array where position i holds the product of every element except the one at i. Do not use division (an element may be 0).

Constraints

  • 1 ≤ n ≤ 10 and −9 ≤ values ≤ 9, so every product fits in a 32-bit integer (|product| ≤ 9⁹)

Examples

[2, 3, 4] → [12, 8, 6]

[5, 0, 2] → [0, 10, 0]

Show the solution

Prefix and suffix products

result[i] = prefix(i) × suffix(i). Compute prefixes forwards into the result, then fold suffixes in backwards with one running variable.

Why it is correct

After the forward pass result[i] is the product of a[0..i). The backward pass multiplies result[i] by the product of a(i..n), so it becomes the product of all elements except a[i].

Complexity

Time O(n), extra space O(1) besides the output. Two passes, each O(n).

Edge cases

  • One element: the empty product, 1.
  • One zero: only that position is non-zero.
  • Two zeros: every position is 0.

Common mistakes

  • Dividing the total product by a[i] (division by zero, and wrong with zeros).
  • Overflow on larger inputs: use 64-bit integers or arbitrary precision.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class ProductExceptSelf
{
    /// <summary>result[i] = product of every element except values[i], without division. O(n), O(1) extra space.</summary>
    public static int[] Compute(int[] values)
    {
        int n = values.Length;
        var result = new int[n];
        int prefix = 1;
        for (int i = 0; i < n; i++)
        {
            result[i] = prefix; // product of values[0..i)
            prefix *= values[i];
        }
        int suffix = 1;
        for (int i = n - 1; i >= 0; i--)
        {
            result[i] *= suffix; // times the product of values(i..n)
            suffix *= values[i];
        }
        return result;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/ProductExceptSelf.cs

from collections.abc import Sequence
 
 
def compute(values: Sequence[int]) -> list[int]:
    """result[i] = product of every element except values[i], without division. O(n), O(1) extra space."""
    n = len(values)
    result = [0] * n
    prefix = 1
    for i in range(n):
        result[i] = prefix  # product of values[:i]
        prefix *= values[i]
    suffix = 1
    for i in range(n - 1, -1, -1):
        result[i] *= suffix  # times the product of values[i + 1:]
        suffix *= values[i]
    return result

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/product_except_self.py

package dev.bekadan.dsa.problems;
 
public final class ProductExceptSelf {
    private ProductExceptSelf() {
    }
 
    /** result[i] = product of every element except values[i], without division. O(n), O(1) extra space. */
    public static int[] compute(int[] values) {
        int n = values.length;
        int[] result = new int[n];
        int prefix = 1;
        for (int i = 0; i < n; i++) {
            result[i] = prefix; // product of values[0..i)
            prefix *= values[i];
        }
        int suffix = 1;
        for (int i = n - 1; i >= 0; i--) {
            result[i] *= suffix; // times the product of values(i..n)
            suffix *= values[i];
        }
        return result;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/ProductExceptSelf.java

#pragma once
 
#include <cstddef>
#include <span>
#include <vector>
 
namespace bekadan::dsa::problems {
 
// result[i] = product of every element except values[i], without division. O(n), O(1) extra space.
inline std::vector<int> product_except_self(std::span<const int> values) {
    const std::size_t n = values.size();
    std::vector<int> result(n);
    int prefix = 1;
    for (std::size_t i = 0; i < n; ++i) {
        result[i] = prefix;  // product of values[0, i)
        prefix *= values[i];
    }
    int suffix = 1;
    for (std::size_t i = n; i-- > 0;) {
        result[i] *= suffix;  // times the product of values(i, n)
        suffix *= values[i];
    }
    return result;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/product_except_self.hpp