ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from collections import deque
a = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3
dq = deque()
out = []
for i, x in enumerate(a):
    while dq and dq[0] <= i - k:
        dq.popleft()
    while dq and a[dq[-1]] <= x:
        dq.pop()
    dq.append(i)
    if i >= k - 1:
        out.append(a[dq[0]])
print(out)
  1. A. [3, 3, -1, 5, 5, 6, 7]
  2. B. [1, 3, 5, 5, 6, 7]
  3. C. [3, 3, 5, 3, 6, 7]
  4. D. [3, 3, 5, 5, 6, 7]

Correct answer: D. [3, 3, 5, 5, 6, 7]

The deque holds indices of a decreasing sequence of values inside the window. The front is always the window maximum, and indices that leave the window are removed from the left, so each step is amortised O(1).

More Python Programming questions

Exams that ask this topic