Six windows, one linear scan: a deque of decreasing indices keeps the current window's maximum sitting at its front.
Keep only future champions: discard what's smaller, evict what's stale, read the front.
Brute force rescans all k elements per window. But most of those elements are irrelevant: anything smaller and older than a newcomer can never be any future window's maximum, and anything outside the window is already dead. The deque stores exactly the survivors — indices in order, values decreasing.
Start with the canonical [1, 3, −1, −3, 5, 3, 6, 7], k = 3. Step slowly and watch indices get evicted or popped exactly when they stop mattering — then try the falling preset, where almost nothing survives.
from collections import deque
def maxSlidingWindow(nums, k):
dq = deque() # indices, values decreasing, all inside the window
ans = []
for i, x in enumerate(nums):
if dq and dq[0] <= i - k: # front slid out of the window
dq.popleft()
while dq and nums[dq[-1]] < x: # newcomer dominates the back
dq.pop()
dq.append(i)
if i >= k - 1: # window [i-k+1, i] is full
ans.append(nums[dq[0]])
return ans
Ties keep the older index (strict < pop): it answers earlier windows first and leaves on schedule anyway.
dq[0] <= i - kThe front index is a full window behind — popleft before pushing the newcomer.nums[dq[-1]] < xPop the back while it is smaller; the newcomer is larger and newer, so it outlives everything it pops.ans ← nums[dq[0]]Recorded only once the window is full (i ≥ k−1), giving exactly n−k+1 answers.When 5 arrives at index 4 it pops −3 and −1 from the back, and index 1 has slid out of the window — so the front becomes 5. Each window's answer is simply whatever sits at the deque front.
The smallest valid input: nothing to evict, nothing to pop — index 0 is pushed and the single full window reads the front. Also confirms the answer length is n−k+1 = 1.
“I keep a deque of indices with decreasing values, all inside the current window. For each new element I evict the front if it slid out, pop the back while it is smaller than the newcomer, then push. Once the window is full the front is always its maximum. Each index is pushed and popped at most once, so it runs in linear time with O(k) extra space.”