10. Product of Array Except Self

Difficulty:MediumPattern:Prefix/Suffix AccumulationTime:O(n)Space:O(1)

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i], without using division in $O(n)$ time.

How It Works & Algorithmic Design

Solves using Prefix and Suffix Product Accumulation:

  1. Left Products Pass: Create result array res. Set res[0] = 1. For $i$ from $1$ to $n-1$, compute res[i] = res[i - 1] * nums[i - 1] (stores product of all elements to the left of $i$).
  2. Right Products Pass: Maintain running right = 1. Loop backwards from $n-1$ down to $0$:
    • res[i] = res[i] * right.
    • Update right = right * nums[i].
  3. Return: res contains total prefix $\times$ suffix products for every index.

Why This Approach Works Best

Avoids division by zero crashes and achieves linear $O(n)$ time using $O(1)$ extra memory (excluding output array).

Example Walkthrough

Input

nums = [1, 2, 3, 4]

Target input.

Left Pass

res = [1, 1, 2, 6]

Products of elements to the left.

Right Pass

res = [24, 12, 8, 6]

Multiplied by suffix running products.

Output

[24, 12, 8, 6]

Products except self.

Answer: Product of array except self

function productExceptSelf(nums) {
  const n = nums.length;
  const res = new Array(n);
  res[0] = 1;
  for (let i = 1; i < n; i++) {
    res[i] = res[i - 1] * nums[i - 1];
  }
  let right = 1;
  for (let i = n - 1; i >= 0; i--) {
    res[i] *= right;
    right *= nums[i];
  }
  return res;
}

Combine left prefix products and right suffix products in two simple passes.

Key Takeaways
  • Combines prefix product and suffix product without using division.

  • Reuses output array space to achieve true $O(1)$ auxiliary memory.

  • Linear time complexity $O(n)$.