awelgorithms

Prefix products with a zero trap

Updated

A range product is P[R] / P[L-1] only when no zero sits in the range. Any zero inside makes the product 0, and a zero before the range makes the division 0/0.

What to focus on

Keep a prefix product of the non-zero values and a prefix count of zeros. If the range contains a zero the answer is 0; otherwise divide the non-zero prefix products.

Worked examples

no zero

a = [4, 1, 9], L = 1, R = 2
  1. no zero in range
  2. 36 / 4

Result: 9

zero inside

a = [1, 0, 2], L = 1, R = 2
  1. index 1 is 0

Result: 0

zero before

a = [1, 0, 2], L = 2, R = 2
  1. zero count equal at L−1 and R
  2. non-zero prefix 2 / 1

Result: 2

Try it

Write rangeProduct(a, L, R). a is an array of integers that may contain zeros. L and R are inclusive indices. Return the product of a[L..R] using a prefix product over non-zero values plus a prefix count of zeros, without dividing by zero. On [4, 1, 9] with [1, 2] return 9. On [1, 0, 2] with [1, 2] return 0. On [1, 0, 2] with [2, 2] return 2.

a is a non-empty array of integers; zeros may appear. 0 ≤ L ≤ R < n.