Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the maximum of every window of size k in a stream of readings.

Problem: Return the maximum of every window of size k in a stream of readings.
from collections import deque
def win_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(win_max([4, 2, 12, 3, 8, 1, 7], 3))
What is printed?
  1. A. [12, 12, 8, 8, 7]
  2. B. [4, 12, 12, 8, 8]
  3. C. [12, 12, 12, 8, 8]
  4. D. [12, 12, 12, 8, 7]

Correct answer: C. [12, 12, 12, 8, 8]

A deque keeps indices of decreasing values; the front is the window maximum and is dropped once it slides out. Windows: [4,2,12]=12, [2,12,3]=12, [12,3,8]=12, [3,8,1]=8, [8,1,7]=8. Each index is pushed and popped once, so O(n) versus O(nk) for rescanning each window.

More Coding Interview Problems questions

Exams that ask this topic