Data Structures & AlgorithmsHardProduct Company SDE · Amazon-style OA

Problem: Find the maximum of every window of size 3 in the array below, printing the list of window maxima.

Problem: Find the maximum of every window of size 3 in the array below, printing the list of window maxima.
from collections import deque
def sliding_max(a, k):
    dq, out = deque(), []
    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]])
    return out
print(sliding_max([1, 3, -1, -3, 5, 3, 6, 7], 3))
What is printed?
  1. A. [3, 3, 5, 3, 6, 7]
  2. B. [1, 3, 3, 5, 5, 6]
  3. C. [3, 3, 5, 5, 5, 7]
  4. D. [3, 3, 5, 5, 6, 7]

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

The monotone deque keeps indices with decreasing values, so each window's front is its maximum. The six windows give maxima 3, 3, 5, 5, 6, 7.

More Coding Interview Problems questions

Exams that ask this topic