KatInterview

Leave-One-Out Products Without Using Division

Arrays & HashingAuto-graded · 19 test cases
MediumAuto-gradedArrays & Hashingprefix-productsuffix-productarray

Last updated

Build an array where each entry is the product of all other entries, without division, in linear time, using prefix and suffix running products.

Leave-One-Out Products

You are given a list of integers values. Produce a new list answer of the same length where answer[i] is the product of every element of values except the one at position i.

The division operator must not be used. Aim for linear time.

Rules

  • answer[i] multiplies together all values[j] with j != i.
  • Zeros and negative numbers are allowed and follow ordinary multiplication rules. For example, if the list contains exactly one zero, only the entry at that zero's position can be nonzero. If it contains two or more zeros, every entry is 0.
  • Return the resulting list of integers.

Constraints

  • 2 <= len(values) <= 10^5
  • -10 <= values[i] <= 10
  • Every prefix product and every suffix product fits in a signed 64-bit integer.
  • Do not use division.
  • Target O(n) time and O(1) extra space, not counting the returned list.

Examples

Example 1

Input: leave_one_out_products([1, 2, 3, 4])

Output: [24, 12, 8, 6]

Example 2

Input: leave_one_out_products([-1, 1, 0, -3, 3])

Output: [0, 0, 9, 0, 0]

Hints

Hint 1

Split the product for index i into two parts: everything to its left and everything to its right.

Hint 2

Walk left to right keeping a running product, storing it in the output slot before you multiply the current element into it.

Hint 3

Walk right to left with a single running suffix variable, multiplying it into the output slot before folding in the current element. Zeros need no special handling.