~/problems / Sliding window

Sliding Window Maximum

hard ~40 min

Write max_sliding_window(nums: list[int], k: int) -> list[int].

Slide a window of exactly k consecutive elements across nums from left to right, one step at a time. Return the maximum of each window, in order (so the result has len(nums) - k + 1 values).

Example: nums = [4, 2, 12, 3, 8, 1, 7], k = 3 gives [12, 12, 12, 8, 8]. With k = 1 the answer is nums itself.

Constraints: 1 <= k <= len(nums) <= 2 * 10^5, values fit in a normal int (may be negative).

Aim for O(n). Recomputing max of each window is O(n·k) and too slow for the large test (big k).

Show hint

once a larger value arrives, any smaller value before it can never be a window maximum again. Keep only the indexes that could still matter, in an order that lets you add and drop them at either end.

Topic: Sliding window. Grow right, shrink left while invalid; monotonic deque for window max/min.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc