Build products except self
For each integer array position, return the product of every other value without using division.
Course progress
Problem 90 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [1, 2, 3, 4]
Expected output
24 12 8 6
What is happening?
At each position multiply the other three values: 2x3x4=24, 1x3x4=12, 1x2x4=8, and 1x2x3=6.
Solution strategy
Build the right mental model
Store the product to the left of each position, then scan backward while multiplying by a running product from the right.
Core concepts
arrays · prefix products
Complexity
Time O(n), space O(1) excluding the output array.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for product-array-except-self
using System;
class Program
{
static int[] ProductExceptSelf(int[] numbers)
{
int[] result = new int[numbers.Length];
int prefix = 1;
for (int i = 0; i < numbers.Length; i++)
{
result[i] = prefix;
prefix *= numbers[i];
}
int suffix = 1;
for (int i = numbers.Length - 1; i >= 0; i--)
{
result[i] *= suffix;
suffix *= numbers[i];
}
return result;
}
static void Main()
{
Console.WriteLine(string.Join(" ", ProductExceptSelf(new[] { 1, 2, 3, 4 })));
}
}Knowledge check
Questions students often ask
What is the main idea behind build products except self?
Store the product to the left of each position, then scan backward while multiplying by a running product from the right.
What is the time and space complexity of this solution?
Time O(n), space O(1) excluding the output array.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.