THN Interview Prep

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]

indexprefix so far (before × nums[index])answer after pass1
011
111
222
366

Second pass: multiply by suffix from right.

indexsuffix from rightfinal answer
316×1=6
242×4=8
1121×12=12
0241×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

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?

On this page