Data Structures & AlgorithmsVery hardProduct company OA

Problem: Count contiguous subarrays whose max − min ≤ k, using two monotonic deques and a shrinking left edge.

Problem: Count contiguous subarrays whose max − min ≤ k, using two monotonic deques and a shrinking left edge.
from collections import deque
def count(a, k):
    mx, mn, lo, c = deque(), deque(), 0, 0
    for hi, x in enumerate(a):
        while mx and a[mx[-1]] <= x: mx.pop()
        while mn and a[mn[-1]] >= x: mn.pop()
        mx.append(hi); mn.append(hi)
        while a[mx[0]] - a[mn[0]] > k:
            lo += 1
            if mx[0] < lo: mx.popleft()
            if mn[0] < lo: mn.popleft()
        c += hi - lo + 1
    return c
print(count([4, 2, 2, 5, 3, 6, 1], 2), count([1, 1, 1], 0))
What is printed?
  1. A. 9 6
  2. B. 11 6
  3. C. 11 3
  4. D. 13 6

Correct answer: B. 11 6

For each right end the window [lo, hi] is the longest valid one ending there (shrinking only helps, so lo never moves back) and contributes hi − lo + 1 subarrays. The max-deque keeps decreasing values and the min-deque increasing values, so both extremes are read in O(1); every index enters and leaves each deque once → O(n). For [4, 2, 2, 5, 3, 6, 1] with k = 2 the total is 11, which brute force confirms; for three equal values every one of the 6 subarrays qualifies.

More Coding Interview Problems questions

Exams that ask this topic