238. Product of Array Except Self
At a Glance
- Topic: arrays-hashing
- Pattern: Prefix Sum / Suffix (prefix–suffix products)
- Difficulty: Medium
- Companies: Amazon, Meta, Google, Apple, Microsoft
- Frequency: Very High
- LeetCode: 238
Problem (one-liner)
Given an integer array numbers, return an array answer where answer[index] equals the product of all elements of numbers except numbers[index]. Solve without division; output fits in 32-bit signed.
Recognition Cues
- "Product of all except self", "no division operator"
- Left products × right products or running prefix/suffix
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — recompute product per index —
O(n²)time. - Better — total product / self —
O(n)but invalid when zeros or problem forbids division. - Optimal — prefix products left-to-right, suffix right-to-left —
O(n)time /O(1)extra excluding output.
Optimal Solution
Go
package main
func productExceptSelf(numbers []int) []int {
length := len(numbers)
answer := make([]int, length)
prefix := 1
for index := 0; index < length; index++ {
answer[index] = prefix
prefix *= numbers[index]
}
suffix := 1
for index := length - 1; index >= 0; index-- {
answer[index] *= suffix
suffix *= numbers[index]
}
return answer
}JavaScript
function productExceptSelf(numbers) {
const length = numbers.length;
const answer = new Array(length);
let prefix = 1;
for (let index = 0; index < length; index++) {
answer[index] = prefix;
prefix *= numbers[index];
}
let suffix = 1;
for (let index = length - 1; index >= 0; index--) {
answer[index] *= suffix;
suffix *= numbers[index];
}
return answer;
}Walkthrough
Input: numbers = [1, 2, 3, 4]
| index | prefix so far (before × nums[index]) | answer after pass1 |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 6 | 6 |
Second pass: multiply by suffix from right.
| index | suffix from right | final answer |
|---|---|---|
| 3 | 1 | 6×1=6 |
| 2 | 4 | 2×4=8 |
| 1 | 12 | 1×12=12 |
| 0 | 24 | 1×24=24 |
Result: [24, 12, 8, 6].
Edge Cases
- Array length 2 — trivial swap of products.
- Contains zero(s) — prefix/suffix handles without division.
- Negative numbers — same algorithm.
Pitfalls
- Division approach fails on zeros or when forbidden.
- Integer overflow in languages without big integers — problem usually guarantees fit.
Similar Problems
- 152. Maximum Product Subarray — track min/max running products.
- 053. Maximum Subarray — linear scan accumulation pattern.
- 121. Best Time to Buy and Sell Stock — prefix min idea.
Variants
- Return modulo prime.
- Matrix version row/col products.
Mind-Map Tags
#arrays #prefix-sum #suffix #product #linear
Last updated on
Spotted something unclear or wrong on this page?