Deque & Sliding Window Maximum
DSA · Advanced
Definition
A deque allows O(1) push/pop at both ends; a monotonic deque gives the max of each window.
Classic hard interview problem solved in linear time.
Diagram
Flowchart
Example: Window max k=3
from collections import deque
a, k = [1, 3, -1, -3, 5], 3
dq, out = deque(), []
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)Output: [3, 3, 5]
Complexity
O(n)
Key points
- collections.deque is O(1) at both ends
- list.pop(0) is O(n) — avoid it
Interview questions
Why not a heap?
A heap gives O(n log k); the deque gives O(n).