Polski

Product of all except self

For every position compute the product of the other elements – without division and in linear time. Prefix and suffix products, plus zeros.

medium · typescript · javascript · python · csharp · java · go · 20 XP

In a pricing model each of n factors (discounts, rates, multipliers) affects the final price. An analyst wants to know the outcome without each factor – for every one of them. Dividing the total product is out: factors can be zero.

Task

For an integer array nums return an array result where result[i] is the product of all elements except nums[i].

  • No division, O(n) time.
  • The input array must not be modified.
  • For a single element the result is [1] (the empty product), for an empty array – an empty array.

Signatures: productExceptSelf(nums) (JS/TS), product_except_self(nums) (Python), Solution.ProductExceptSelf (C#), Solution.productExceptSelf (Java), ProductExceptSelf (Go).

Examples

numsResult
[1, 2, 3, 4][24, 12, 8, 6]
[-1, 1, 0, -3, 3][0, 0, 9, 0, 0]
[0, 4, 0][0, 0, 0]
[5][1]

Constraints

  • 0 ≤ n ≤ 100,000, -30 ≤ nums[i] ≤ 30.
  • The product of every prefix and suffix fits in a 32-bit int.

Expected complexity

O(n) time, O(1) extra memory besides the result array.