Skip to main content

Product of Array Except Self

MediumArraysPrefix sum303 tests

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

You must write it without using division, and it should run in O(n).

Example 1

text

answer[0] = 2*3*4 = 24, answer[1] = 1*3*4 = 12, and so on.

Example 2

text

Think about what sits to the left of each index and what sits to the right, and how two passes can give you both.

Examples

Example 1

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

answer[0] = 2*3*4 = 24, answer[1] = 1*3*4 = 12, answer[2] = 1*2*4 = 8, answer[3] = 1*2*3 = 6.

Example 2

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

Every position except the zero itself includes the zero in its product. At the zero, the product of the others is -1*1*-3*3 = 9.

Example 3

Input:
[0,0]
Output:
[0,0]

With two zeros, every answer is zero.

Constraints

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

Run checks your code against the 3 examples. Submit checks it against all 303 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.