Sliding Window Maximum
Sliding Window Maximum is LeetCode 239 (Hard). A window of size k slides over nums one step at a time, from the left end to the right end. Return the largest value in each window.
- There are
n - k + 1windows, so the answer has that many values.
With n and k both up to 10⁵, rescanning each window costs up to O(n · k), about 2.5 × 10⁹ steps. The answer has to come from something that updates in O(1) per step on average.
- 1 <= nums.length <= 10⁵
- -10⁴ <= nums[i] <= 10⁴
- 1 <= k <= nums.length
Intuition
When a new value x enters, every older value smaller than or equal to x can never be a maximum again: x is at least as large and stays in the window longer. Throw those values away.
What survives is a list whose values strictly decrease from oldest to newest, kept in a deque:
- Front: the largest value still in the window, so it is the answer for this window.
- Back: where new values enter, after removing the smaller ones.
- Expiry: the deque stores indices, so when the front's index drops out of the window it is removed from the front.
Each index enters once and leaves once, so the whole pass is O(n).
"Best value in every window" or "next greater value" questions, where a newer, bigger element makes older, smaller ones useless. That dominance is the signal for a monotonic deque or stack.
Approach
Before reading on, slide a window of 3 over [1,3,-1,-3,5] by hand. Each time a value enters, cross out the values that can never be the answer again. What order are the survivors always in?
Two ways to solve it
Keep only indices that can still become a window maximum, in decreasing value order.
- Front: always the answer.
- Each index: added once, removed once.
The expected answer at Hard level.
Push every value with its index; before reading the top, pop entries whose index has left the window.
- Familiar: no new data structure to reason about.
- Cost: stale entries can pile up, so the heap can reach n entries.
The usual first idea; it passes but is slower.
The deque is O(n) because it removes useless values for good; the heap keeps them until they reach the top. The steps, code and demo follow the deque; the heap code comes after the demo.
Keep a deque of indices
Store indices, not values. The index tells you when an element has left the window, and nums[index] still gives its value. Values in the deque strictly decrease from front to back.
Remove smaller values from the back
Before adding index i, pop from the back while nums[back] <= nums[i]. Those elements are not larger than nums[i] and will leave the window earlier, so none of them can ever be a window maximum again.
Add the new index
Append i at the back. The deque is still in decreasing order, because everything left in front of i is larger than nums[i].
Drop the front once it leaves the window
The window ending at i covers indices i - k + 1 to i. If the front index equals i - k, it has just slid out, so pop it from the front. At most one index leaves per step, so one check is enough.
Record the front as the answer
From i = k - 1 on, every step completes a window. The front is the largest value still inside it, so append nums[front] to the result.
Code in Python, C++ and Java
Max-heap with lazy removal
The heap holds (value, index) pairs ordered by value, largest on top (Python negates values to get a max-heap). Entries are not removed when they leave the window. Instead, before reading the top, pop it while its index is at or before i - k.
Common pitfalls
Storing values instead of indices
dq.append(x)
if dq[0] == nums[i - k]:
dq.popleft()dq.append(i)
if dq[0] == i - k:
dq.popleft()With values you cannot tell which copy of a repeated value left the window. On nums = [3,1,3], k = 2, the leaving 3 matches the newer 3 still at the front, so it is popped and the next window has no maximum to read.
Expiring with the wrong boundary
if dq[0] < i - k:
dq.popleft()if dq[0] == i - k:
dq.popleft()The window ending at i starts at i - k + 1, so index i - k is already outside. Testing < i - k keeps it one step too long: on [5,1,2] with k = 2 the second window reports 5 instead of 2.
Edge cases
[4,4,4] with k = 2Popping with <= keeps only the newest copy, which stays in the window longest. The answer is [4, 4].
k = 1Every window is a single element. Each new index pops the previous one, or expires it, so the answer is nums itself.
Complexity
while loop runs at most n times in total. The deque never holds more than k indices. The result list of n - k + 1 values is not counted.Sliding Window Maximum FAQ
Why is it O(n) when there is a while loop inside the for loop?
Count pops instead of loop rounds. Every pop removes an index that was pushed earlier, and each index is pushed exactly once, so there are at most n pops over the whole run, however they are spread across steps.
How do I get the sliding window minimum instead?
Flip the comparison: pop from the back while nums[back] >= x. The deque then holds increasing values and its front is the window minimum.
Is this the same as maximum of all subarrays of size k?
Yes. Many practice sites use that name for the same task: every contiguous block of k elements, and the largest value in each, in order. The deque method carries over unchanged.
Is there an O(n) method without a deque?
Yes. Cut the array into blocks of size k and precompute, for each index, the maximum from the start of its block and the maximum to the end of its block. Any window covers the end of one block and the start of the next, so its maximum is the larger of two precomputed values. It uses O(n) extra memory.