LeetCode #239 Hard

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 + 1 windows, 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.

Constraints
  • 1 <= nums.length <= 10⁵
  • -10⁴ <= nums[i] <= 10⁴
  • 1 <= k <= nums.length
dequemonotonic-queuesliding-window
Open on LeetCode ↗
02

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).

How to spot this pattern

"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.

03

Approach

Try it first

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?

1

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.

2

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.

3

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].

4

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.

5

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.

04

Code in Python, C++ and Java

▶1from collections import deque
▶2 
▶3class Solution:
▶4 def maxSlidingWindow(self, nums, k):
▶5 dq = deque()
▶6 res = []
▶7 for i, x in enumerate(nums):
▶8 while dq and nums[dq[-1]] <= x:
▶9 dq.pop()
▶10 dq.append(i)
▶11 if dq[0] == i - k:
▶12 dq.popleft()
▶13 if i >= k - 1:
▶14 res.append(nums[dq[0]])
▶15 return res
nums, window of 31031-12-3354356677deque, front → backemptywindow maximumsnone yetwindows of 3 over 8 values
k3
windows6
The deque will hold indices of values that could still be a window maximum. Drawn as bars, they always get shorter from front to back, so the front bar is the largest.
nums, window of 31031-12-3354356677deque, front → back1index 0window maximumsnone yetpush 1, window not full yet
deque values1
res[]
Index 0 joins at the back; it is the only index in the deque. Only 1 of 3 values are in, so no window is complete yet.
nums, window of 31031-12-3354356677deque, front → back1index 0poppedwindow maximumsnone yet3 arrives, 1 is not larger → pop 1
x3index 1
deque valuesemptypopped 1
1 (index 0) is not larger than the new 3, and it will leave the window first. Every window that contains it also contains 3, so it can never be the maximum again.
nums, window of 31031-12-3354356677deque, front → back3index 1window maximumsnone yetpush 3, window not full yet
deque values3
res[]
Index 1 joins at the back; it is the only index in the deque. Only 2 of 3 values are in, so no window is complete yet.
nums, window of 31031-12-3354356677deque, front → back3index 1-1index 2window maximums3push -1 → window max 3
deque values3, -1
res[3]
Index 2 joins at the back; everything in front of it is larger, so the bars still get shorter. The window ending at index 2 is complete, and the front bar, 3, is its maximum.
nums, window of 31031-12-3354356677deque, front → back3index 1-1index 2-3index 3window maximums33push -3 → window max 3
deque values3, -1, -3
res[3, 3]
Index 3 joins at the back; everything in front of it is larger, so the bars still get shorter. The window ending at index 3 is complete, and the front bar, 3, is its maximum.
nums, window of 31031-12-3354356677deque, front → back3index 1-1index 2-3index 3poppedwindow maximums335 arrives, -3 is not larger → pop -3
x5index 4
deque values3, -1popped -3
-3 (index 3) is not larger than the new 5, and it will leave the window first. Every window that contains it also contains 5, so it can never be the maximum again.
nums, window of 31031-12-3354356677deque, front → back3index 1-1index 2poppedwindow maximums335 arrives, -1 is not larger → pop -1
x5index 4
deque values3popped -1
-1 (index 2) is not larger than the new 5, and it will leave the window first. Every window that contains it also contains 5, so it can never be the maximum again.
nums, window of 31031-12-3354356677deque, front → back3index 1poppedwindow maximums335 arrives, 3 is not larger → pop 3
x5index 4
deque valuesemptypopped 3
3 (index 1) is not larger than the new 5, and it will leave the window first. Every window that contains it also contains 5, so it can never be the maximum again.
nums, window of 31031-12-3354356677deque, front → back5index 4window maximums335push 5 → window max 5
deque values5
res[3, 3, 5]
Index 4 joins at the back; it is the only index in the deque. The window ending at index 4 is complete, and the front bar, 5, is its maximum.
nums, window of 31031-12-3354356677deque, front → back5index 43index 5window maximums3355push 3 → window max 5
deque values5, 3
res[3, 3, 5, 5]
Index 5 joins at the back; everything in front of it is larger, so the bars still get shorter. The window ending at index 5 is complete, and the front bar, 5, is its maximum.
nums, window of 31031-12-3354356677deque, front → back5index 43index 5poppedwindow maximums33556 arrives, 3 is not larger → pop 3
x6index 6
deque values5popped 3
3 (index 5) is not larger than the new 6, and it will leave the window first. Every window that contains it also contains 6, so it can never be the maximum again.
nums, window of 31031-12-3354356677deque, front → back5index 4poppedwindow maximums33556 arrives, 5 is not larger → pop 5
x6index 6
deque valuesemptypopped 5
5 (index 4) is not larger than the new 6, and it will leave the window first. Every window that contains it also contains 6, so it can never be the maximum again.
nums, window of 31031-12-3354356677deque, front → back6index 6window maximums33556push 6 → window max 6
deque values6
res[3, 3, 5, 5, 6]
Index 6 joins at the back; it is the only index in the deque. The window ending at index 6 is complete, and the front bar, 6, is its maximum.
nums, window of 31031-12-3354356677deque, front → back6index 6poppedwindow maximums335567 arrives, 6 is not larger → pop 6
x7index 7
deque valuesemptypopped 6
6 (index 6) is not larger than the new 7, and it will leave the window first. Every window that contains it also contains 7, so it can never be the maximum again.
nums, window of 31031-12-3354356677deque, front → back7index 7window maximums335567push 7 → window max 7
deque values7
res[3, 3, 5, 5, 6, 7]
Index 7 joins at the back; it is the only index in the deque. The window ending at index 7 is complete, and the front bar, 7, is its maximum.
nums, window of 31031-12-3354356677deque, front → back7index 7window maximums335567answer: 3, 3, 5, 5, 6, 7
result[3, 3, 5, 5, 6, 7]
One maximum per window, 6 in all. Each index was pushed once and popped at most once, so the work is linear in the length of the array.
05

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.

▶1import heapq
▶2 
▶3class Solution:
▶4 def maxSlidingWindow(self, nums, k):
▶5 heap = []
▶6 res = []
▶7 for i, x in enumerate(nums):
▶8 heapq.heappush(heap, (-x, i))
▶9 if i >= k - 1:
▶10 while heap[0][1] <= i - k:
▶11 heapq.heappop(heap)
▶12 res.append(-heap[0][0])
▶13 return res
06

Common pitfalls

Storing values instead of indices

✗ Wrong
dq.append(x)
if dq[0] == nums[i - k]:
    dq.popleft()
✓ Right
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

✗ Wrong
if dq[0] < i - k:
    dq.popleft()
✓ Right
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.

07

Edge cases

Equal values, such as [4,4,4] with k = 2

Popping with <= keeps only the newest copy, which stays in the window longest. The answer is [4, 4].

k = 1

Every window is a single element. Each new index pops the previous one, or expires it, so the answer is nums itself.

08

Complexity

Time
O(n)
Space
O(k)
Each index is pushed once and popped at most once, from the back or the front, so the inner 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.
09

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.