Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Longest subarray whose max − min ≤ limit, using two monotonic deques.

Problem: Longest subarray whose max − min ≤ limit, using two monotonic deques.
from collections import deque
def longest(a, lim):
    mx, mn, l, best = deque(), deque(), 0, 0
    for r, x in enumerate(a):
        while mx and a[mx[-1]] <= x: mx.pop()
        while mn and a[mn[-1]] >= x: mn.pop()
        mx.append(r); mn.append(r)
        while a[mx[0]] - a[mn[0]] > lim:
            l += 1
            if mx[0] < l: mx.popleft()
            if mn[0] < l: mn.popleft()
        best = max(best, r - l + 1)
    return best
print(longest([4, 8, 5, 1, 7, 9, 6], 3))
What is printed?
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 5

Correct answer: A. 3

The windows [8, 5], [7, 9, 6] and so on are checked; [7, 9, 6] has max − min = 3, length 3, and no window of length 4 stays within 3 (e.g. [1, 7, 9, 6] spans 8). The deques give O(n) instead of re-scanning each window.

More Coding Interview Problems questions

Exams that ask this topic