DSA AnimatorDSA animations
Sliding Window Maximum LC #239 Hard Monotonic Deque
Problem

You are given an integer array nums and a window of size k that slides from the very left of the array to the very right, one position at a time. Return the maximum of each window. Aim for O(n) time.

Example 1
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Example 2
Input: nums = [1], k = 1
Output: [1]
Constraints: 1 ≤ nums.length ≤ 10⁵  |  −10⁴ ≤ nums[i] ≤ 10⁴  |  1 ≤ k ≤ nums.length
🪟 Array & window
👑
window
i
🚇 Deque of indices · values always decreasing front → back
⬅FRONT
max 👑
empty
➡BACK
newest
deque operations: 0 brute force would compare: —
👑 current window max🗑️ popped from back (smaller, older)⌛ popped from front (left the window) index is in the deque
Variables
i
—
window
—
deque (idx)
—
nums[front]
—
💡 Step Logic
Press ▶ Play or Next to begin.
✓
Ready
0 / 0
Pick an example and press Play.
Algorithm
1
Deque stores indices; their values are always decreasing front → back
2
For each i: if the front index left the window (≤ i − k), pop it from the front ⌛
3
While the back value ≤ nums[i], pop it from the back 🗑️ (it can never be a max again)
4
Push i to the back
5
Once the window is full (i ≥ k − 1), the answer is nums[front] 👑
Time
O(n)
Space
O(k)
🧠 Why it's O(n)

Every index is pushed once and popped at most once, so the deque does at most 2n operations in total, no matter how big k is. Checking every window directly costs (n − k + 1) · k comparisons, which is O(n·k). The watch-out: store indices, not values, so you can tell when the front has slid out of the window.

⚠️ Edge cases

k = 1 → every element is its own max. k = n → one window, one answer. Decreasing array → nothing is ever popped from the back and the deque fills up to k. Duplicates → using ≤ drops the older copy, which is safe because the newer one lasts longer.

How to solve Sliding Window Maximum

LeetCode 239 · Hard · Queue · Pattern: Monotonic Deque

Why the obvious approach is slow

Scanning every window for its maximum is O(n) times k. A heap works in O(n log n), but a deque does it in linear time.

The key idea

Keep a deque of indexes whose values are decreasing from front to back. Before adding a new number, pop smaller values from the back, because they can never be a maximum again. Pop the front if it has slid out of the window. The front is always the maximum of the current window.

Remember

A monotonic deque keeps candidates in decreasing order. Smaller values behind a bigger, newer one can never win.

Run the animation above on your own input, or watch the 1:40 video explanation of Sliding Window Maximum with a dry run and Java code.

More Queue problems