Facebook PixelProduct of Array Except Self — Coding Practice
Product of Array Except SelfMedium

Product of Array Except Self

Medium 24.8k65% acceptance
ArrayPrefix Sum

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

The answer is guaranteed to fit in a 32-bit integer. Solve it without using the division operator and aim for O(n) time.

Example 1
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
answer[0] = 2·3·4 = 24, answer[1] = 1·3·4 = 12, and so on.
Example 2
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
A single zero zeroes out every position that includes it; only the slot at the zero keeps a non-zero product.
Constraints
  • 2 ≤ nums.length ≤ 10⁵
  • -30 ≤ nums[i] ≤ 30
  • The product of any prefix or suffix fits in a 32-bit integer.
Asked atAmazonMetaMicrosoftApple
JavaScript
Loading editor…
Case 1
[1,2,3,4]
expected: [24,12,8,6]
Case 2
[-1,1,0,-3,3]
expected: [0,0,9,0,0]
Case 3
[2,3]
expected: [3,2]
Case 4
[0,0]
expected: [0,0]
Case 5
[1,0]
expected: [0,1]
Case 6
[5,1,4,2]
expected: [8,40,10,20]