Product of Array Except Self
A medium Arrays problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 3
- Core for
- 25 roles
- Platform
- LeetCode
The problem
Given an integer array, construct a new array where each element at index i equals the product of all elements in the original array except the one at i, without using division.
Example 1
- Input
- nums = [1,2,3,4]
- Output
- [24,12,8,6]
- Why
- For index 0, 2*3*4=24; for index 1, 1*3*4=12; for index 2, 1*2*4=8; for index 3, 1*2*3=6.
Example 2
- Input
- nums = [-1,1,0,-3,3]
- Output
- [0,0,9,0,0]
- Why
- The product of all non-zero elements is 9, which lands exclusively at the index holding 0.
Example 3
- Input
- nums = [2,3]
- Output
- [3,2]
- Why
- Each position receives the only remaining other element.
Constraints
- 2 <= nums.length <= 10^5
- -30 <= nums[i] <= 30
How to think about it
Updated 2026-09-09The product of everything except index i splits cleanly into two independent pieces: the prefix product of everything to its left, and the suffix product of everything to its right. Computing running prefix products left-to-right and running suffix products right-to-left assembles the answer for every cell without ever needing arithmetic division.
Approaches, worst first
Brute force exclusion product
time O(n^2) · space O(1)
For each index i, run a nested loop over all indices j != i and multiply them together. Follows the exact specification without allocating extra arrays, but takes quadratic time and scales poorly on large inputs.
Prefix and suffix arrays
time O(n) · space O(n)
Build prefix[i] holding the product of all numbers before i, and suffix[i] holding the product of all numbers after i. Multiply prefix[i] and suffix[i] to populate the result. Linear time, but requires two additional helper arrays.
Single output array two-pass accumulationWrite this one
time O(n) · space O(1)
Fill the output array with prefix products in a forward sweep. Then sweep backwards with a single running integer tracking the suffix product, multiplying it into the corresponding output slot on the fly. Achieves linear time using zero extra memory beyond the output.
Where people lose marks · 3
- Using division by the total product, which crashes on zeros and violates the explicit constraint against using division.
- Incorrectly handling multiple zeros, where every output entry must be 0 rather than reporting non-zero values.
- Initializing prefix or suffix accumulators to 0 instead of 1, resulting in all-zero output arrays.
Full solution
Single output array two-pass accumulation: a forward sweep fills prefix products into the answer, then a backward sweep multiplies in a running suffix product. Linear time, no division, and no extra array beyond the output.
Python
from typing import List
def product_except_self(nums: List[int]) -> List[int]:
n = len(nums)
answer = [1] * n
prefix = 1
for i in range(n):
answer[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(n - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answer
JavaScript
function productExceptSelf(nums) {
const n = nums.length;
const answer = new Array(n).fill(1);
let prefix = 1;
for (let i = 0; i < n; i++) {
answer[i] = prefix;
prefix *= nums[i];
}
let suffix = 1;
for (let i = n - 1; i >= 0; i--) {
answer[i] *= suffix;
suffix *= nums[i];
}
return answer.map((v) => (v === 0 ? 0 : v)); // normalize -0 to 0
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .