Practice · Prefix sums · 2 of 2

Product of Everything Else

You are given a list of integers nums. Return a list answer of the same length, where answer[i] is the product of every number in nums except nums[i].

Don't use division, and aim for O(n) time. (Dividing the total by nums[i] would fail anyway when the list holds a zero.)

Example 1

Input
nums = [2, 3, 4, 5]
Output
[60, 40, 30, 24]
answer[1] is 2 × 4 × 5 = 40.

Example 2

Input
nums = [3, 0, -2, 1]
Output
[0, -6, 0, 0]
Every product except answer[1] includes the zero.

Constraints

  • nums holds 2 to 10⁵ numbers.
  • Every number is between −30 and 30.
  • The product of any run of numbers in nums fits in a 32-bit signed integer (−2³¹ to 2³¹ − 1).