☰ All problems

14. Product of Array Except Self

MediumArrayPrefix Sum

Given an integer array nums, return an array answer where answer[i] is the product of every element of nums except nums[i].

Your algorithm must run in O(n) time and must not use division. Every prefix and suffix product fits in a 32-bit signed integer.

Example 1
Input: nums = [2,3,4,5]
Output: [60,40,30,24]

Explanation: For example, answer[1] = 2 · 4 · 5 = 40.

Example 2
Input: nums = [-2,1,0,3]
Output: [0,0,-6,0]

Explanation: Only the position holding the 0 gets a non-zero product: -2 · 1 · 3 = -6.

Example 3
Input: nums = [1,2,0,4,0]
Output: [0,0,0,0,0]

Explanation: With two zeros, every product includes at least one of them.

Constraints

  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30
  • Every prefix and suffix product of nums fits in a 32-bit signed integer.

Follow-up: Can you do it with O(1) extra space, not counting the output array?

💡 Hint 1

answer[i] is (product of everything to the left of i) × (product of everything to the right of i).

💡 Hint 2

Compute all the left products in one pass and all the right products in a second pass.

💡 Hint 3

To use O(1) extra space besides the output, store the left products in answer first, then sweep from the right with a single running product.

/**
 * @param {number[]} nums
 * @return {number[]}
 */
function productExceptSelf(nums) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc