Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Count contiguous subarrays of positive integers whose product is strictly less than k, using a shrinking window.

Problem: Count contiguous subarrays of positive integers whose product is strictly less than k, using a shrinking window.
def prod_less(a, k):
    if k <= 1: return 0
    p, l, res = 1, 0, 0
    for r, x in enumerate(a):
        p *= x
        while p >= k:
            p //= a[l]; l += 1
        res += r - l + 1
    return res
print(prod_less([4, 3, 5, 2], 30), prod_less([2, 9, 1], 1), prod_less([1, 1, 1], 2))
What is printed?
  1. A. 7 3 6
  2. B. 8 0 6
  3. C. 7 0 6
  4. D. 7 0 3

Correct answer: C. 7 0 6

Because all values are positive, the window product only grows as r moves right, so shrink from the left until it is < k; every subarray ending at r and starting in [l, r] then qualifies (r − l + 1 of them). [4, 3, 5, 2] with k = 30: 4, 3, 5, 2, 12, 15, 10 → 7 (3·5·2 = 30 is not < 30). k ≤ 1 → 0. [1, 1, 1] with k = 2: all 6 subarrays. O(n).

More Coding Interview Problems questions

Exams that ask this topic