Back to ArraysProduct of Array Except Self
Medium

Product of Array Except Self

MediumMust DoPrefix/Suffix Products

Given an array of integers, return a new array where each element is the product of all the other elements, without using division and in O(n) time.

Examples

Example 1

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

Explanation: Each output value is the product of the other three, e.g. index 0's answer 24 = 2*3*4.

Example 2

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

Explanation: Every index except the zero's own position multiplies in that 0, forcing those results to 0; only index 2 (the zero itself) excludes it and gets the product of the rest.

Example 3

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

Explanation: With no zeros, the left/right running products alone reconstruct each answer correctly regardless of sign.

Constraints

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

Loading editor…

Code execution is coming soon.