Product of Array Except Self

Medium Prefix Sum

nums is a list of whole numbers.

Leave out the number at one position and multiply together all the others: that is the product without that position. A position's own number never counts in its product, but an equal number at another position does.

Return the list of the products without each position, in the order of the positions, without using division.

Example 1

Input: nums = [6,-2,5,3]
Output: [-30,90,-36,-60]

Without position 0 the product is -2 × 5 × 3 = -30, without position 1 it is 6 × 5 × 3 = 90, without position 2 it is 6 × -2 × 3 = -36, and without position 3 it is 6 × -2 × 5 = -60.

Example 2

Input: nums = [5,0,2]
Output: [0,10,0]

Example 3

Input: nums = [0,7,0]
Output: [0,0,0]

Constraints

  • 2 ≤ nums.length ≤ 10⁵
  • -20 ≤ nums[i] ≤ 20
  • The absolute values of all the numbers in nums that are not 0, multiplied together, come to at most 2,147,483,647 (2³¹ - 1), so any product of some of the numbers fits in a 32-bit signed integer

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

Watch the explanation

More Prefix Sum

All Prefix Sum problems