Product of Array Except Self Medium 0 attempts
GeeksforGeeks ↗

Product of Array Except Self

Medium Sorting&Searching GeeksforGeeks

You're given an array nums. Build a new array where each position holds the product of every element in nums except the one at that position — and do it without using division.

Input Format
Implement productExceptSelf(nums). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 · Run Sample

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
  • Guaranteed product of any prefix/suffix fits in 32-bit integer
Test Cases (2)
Case 1
Args: [[1,2,3,4]] Expected: [24,12,8,6]
Case 2
Args: [[0,1,2,0]] Expected: [0,0,0,0]

Left and Right Products

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) extra

Saved in this browser only. Private to you.

JavaScript