Skip to problem
←

Product of Array Except Self

Medium 0 attempts

Given an integer array nums, return an array result of the same length where result[i] is the product of every entry except the one at index i.

Exclude exactly one index, not every occurrence of its value. Preserve index order in the result. Values may be negative, zero, or repeated. Solve the problem in linear time without division.

For [1, 2, 3, 4], return [24, 12, 8, 6]. With exactly one zero, only the result at that zero's index can be nonzero; with two or more zeros, every result is zero.

Follow-up: Use constant auxiliary space, excluding the returned array.

Function contract

Implement productExceptSelf(nums).

Output: Return an array where result[i] is the product of all input entries except nums[i], preserving index order.

Example 1

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

Example 2

Input
nums = [0,1,2,0]
Output
[0,0,0,0]
Constraints
  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30
  • Every prefix product, suffix product, and output value fits in a signed 32-bit integer.

Left and Right Products

Every answer is the product of the entries strictly before its index and the entries strictly after it.

In a left-to-right pass, store the product of all earlier entries in result[i], then include nums[i] in the running prefix. In a right-to-left pass, multiply result[i] by the product of all later entries, then include nums[i] in the running suffix. Updating after using each product excludes the current index.

Initialize both running products to 1, the product of an empty side. Zeros and negative values work through ordinary multiplication without division or special-case branches. The input is not modified.

javascript
function productExceptSelf(nums) {
  const n = nums.length,
    result = 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) auxiliary space, plus O(n) for the returned array.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript