Product of Array Except Self

Difficulty: Medium

Given a list of numbers, build a new list where each position holds the product of all the other numbers, everything except the one at that position.

Don't use division. "Total product divided by nums[i]" is tempting, but it breaks when the list contains a zero.

Examples

Input: nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]

For index 0: 234 = 24. For index 1: 134 = 12. And so on for each position.

Input: nums = [-1, 1, 0, -3, 3]
Output: [0, 0, 9, 0, 0]

Every position except index 2 includes the 0 from the list in its product, so it comes out to 0. Index 2 excludes that 0, leaving -1 * 1 * -3 * 3 = 9.

Constraints

  • 2 <= nums.length <= 10^5

  • The product of any prefix or suffix of nums fits in a standard integer range.

  • You may not use the division operator.

Approach

The answer at each position is the product of everything to its left times the product of everything to its right. Brute force recomputes this from scratch for every position, repeating the same multiplications.

The efficient version reuses work. A left-to-right pass stores at each position the running product of everything before it. A right-to-left pass then multiplies in the running product of everything after it. Each position ends up with the product of all other numbers, with no division.

Solutions

Brute Force - Recompute Each Product

For each position, loop over the whole list and multiply every number except the one at that position.

function productExceptSelf(nums) {
  const n = nums.length;
  const result = new Array(n).fill(1);

  for (let i = 0; i < n; i++) {
    let product = 1;
    for (let j = 0; j < n; j++) {
      if (j !== i) {
        product *= nums[j];
      }
    }
    result[i] = product;
  }

  return result;
}

Time: O(n²) · Space: O(1) extra space, beyond the output array

Optimal - Prefix and Suffix Products

A left-to-right pass fills the output with the running product of everything before each position. A right-to-left pass multiplies in the running product of everything after it. Each index then holds the product of all other numbers.

function productExceptSelf(nums) {
  const n = nums.length;
  const result = new Array(n).fill(1);

  let prefix = 1;
  for (let i = 0; i < n; i++) {
    result[i] = prefix;
    prefix *= nums[i];
  }

  let suffix = 1;
  for (let i = n - 1; i >= 0; i--) {
    result[i] *= suffix;
    suffix *= nums[i];
  }

  return result;
}

Time: O(n) · Space: O(1) extra space, beyond the output array