Data Structures & AlgorithmsVery hardCodeforces Div2 D · TCS NQT

A monotonic deque computes the minimum of each window of size 3.

A monotonic deque computes the minimum of each window of size 3.
from collections import deque
a = [4, 2, 12, 11, -5, 7]
k = 3
dq = deque(); out = []
for i, x in enumerate(a):
    while dq and a[dq[-1]] >= x: dq.pop()
    dq.append(i)
    if dq[0] <= i - k: dq.popleft()
    if i >= k - 1: out.append(a[dq[0]])
print(out)
What is printed?
  1. A. [2, 2, -5, -5]
  2. B. [12, 12, 12, 11]
  3. C. [2, 2, -5]
  4. D. [2, 2, 11, -5, -5]

Correct answer: A. [2, 2, -5, -5]

The deque keeps indices of increasing values, so its front is the window minimum. The first variant pops with the wrong comparison and returns maxima; the others index the wrong range or never remove stale entries.

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

Exams that ask this topic