Data Structures & AlgorithmsVery hardProduct company OA

A monotonic deque reports the maximum of every window of 3 readings and counts deque removals. What is printed?

A monotonic deque reports the maximum of every window of 3 readings and counts deque removals. What is printed?
from collections import deque
def win_max(a, k):
    dq, out, pops = deque(), [], 0
    for i, x in enumerate(a):
        while dq and a[dq[-1]] <= x: dq.pop(); pops += 1
        dq.append(i)
        if dq[0] <= i - k: dq.popleft(); pops += 1
        if i >= k - 1: out.append(a[dq[0]])
    return out, pops
print(*win_max([5, 1, 3, 2, 6, 2, 2, 4, 1], 3))
  1. A. [5, 3, 6, 6, 6, 4, 4] 9
  2. B. [5, 3, 6, 6, 6, 4, 4] 7
  3. C. [5, 3, 6, 6, 6, 6, 4] 7
  4. D. [5, 5, 6, 6, 6, 4, 4] 7

Correct answer: B. [5, 3, 6, 6, 6, 4, 4] 7

The deque holds indices with strictly decreasing values; a new reading evicts every smaller-or-equal one from the back, and the front is dropped once it falls out of the window. Windows: [5,1,3]→5, [1,3,2]→3, [3,2,6]→6, [2,6,2]→6, [6,2,2]→6, [2,2,4]→4, [2,4,1]→4. Each index enters once and leaves at most once, so total removals ≤ n; here 7 (5 back pops + 2 front expiries), which is why the whole pass is O(n) even though the inner while looks quadratic.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic