Skip to main content
←Architecture WorkspaceArchOSWorkspaces/
Sign in
ALGORITHM CANVAS · SLIDING WINDOW + DEQUE · TIME O(N) · SPACE O(K)
Sliding Window Maximum (Monotonic Deque)
Keep indices in strictly decreasing value order inside a deque. Front is always the current window max; each element enters and leaves at most once.
NUMS (8 ELEMENTS)1[0]i ▼3[1]-1[2]-3[3]5[4]3[5]6[6]7[7]DQ (1):0
STEP 1/8 · L6
nums=[1,3,-1,-3,5,3,6,7]k=3i=0x=1dq=[0]out=[]
PYTHON 3.12 · INSTANT PREVIEW
1from collections import deque
2
3def max_window(nums, k):
4 dq = deque()
5 out = []
6 for i, x in enumerate(nums):
7 while dq and dq[0] <= i - k:
8 dq.popleft()
9 while dq and nums[dq[-1]] <= x:
10 dq.pop()
11 dq.append(i)
12 if i >= k - 1:
13 out.append(nums[dq[0]])
14 return out