Sliding Window Maximum (LeetCode 239): Solution and Explanation
Given an integer array and a window size k, slide a window of length k from the left end to the right end one step at a time. Return the maximum value inside the window at each position, giving n minus k plus 1 results.
Watch it run step by step
Try your own input and write the code →Intuition
The direct approach scans all k elements of each window to find its maximum, which costs O(n × k). A max-heap improves that to O(n log n) if you lazily discard entries that have slid out of the window, but there is a linear solution hiding in a simple observation about which elements could ever be the answer.
Suppose the window contains an element x, and later a larger element y enters. From that moment on, x can never be the maximum of any window: every future window that still contains x also contains y, because y arrived later and will leave later. So x is useless and can be thrown away. Applying that rule continually leaves you with candidates in decreasing order of value, from oldest to newest.
A deque holding indices captures this. When a new index arrives, pop smaller values off the back, since the newcomer dominates them, and then append it. The front of the deque is then always the largest value among the remaining candidates. Before reading it, drop the front if its index has fallen out of the window. Every index is pushed and popped at most once, so the whole pass is linear.
Approach: Monotonic decreasing deque of indices
- Create an empty
resultlist and a deque that will store indices whose values are in decreasing order. - For each index
i, pop from the front while the front index is less thani - k + 1, meaning it is outside the window. - Pop from the back while the value at the back index is smaller than
nums[i], since those values can never be a maximum again. - Append
ito the back of the deque. - Once
i >= k - 1, the first full window exists, so appendnums[deque[0]]toresulton every step. - Return
resultafter the last index.
Step-by-step example
nums = [1,3,-1,-3,5,3,6,7], k = 3
- i = 0 pushes index 0. At i = 1, value 3 is larger than 1, so index 0 is popped and the deque is [1].
- i = 2 appends index 2 (value -1) behind 3. The first window is complete, so record 3.
- i = 3 appends index 3 (value -3). The front index 1 is still inside the window, so record 3 again.
- i = 4 first drops index 1 because it is outside the window. Value 5 then pops -3 and -1 off the back, leaving [4]. Record 5.
- i = 5 appends index 5 (value 3) and records 5. At i = 6, value 6 pops 3 and 5, leaving [6], and records 6.
- i = 7 has value 7, which pops 6, so the deque is [7] and 7 is recorded. The result is [3,3,5,5,6,7].
Code: Python, Java, C++
1class Solution:
2 def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
3 result = []
4 deque = collections.deque() # stores indices
5 for i in range(len(nums)):
6 # Remove indices outside current window
7 while deque and deque[0] < i - k + 1:
8 deque.popleft()
9 # Remove smaller elements from back
10 while deque and nums[deque[-1]] < nums[i]:
11 deque.pop()
12 deque.append(i)
13 # Add max to result when window is complete
14 if i >= k - 1:
15 result.append(nums[deque[0]])
16 return result1class Solution {
2 public int[] maxSlidingWindow(int[] nums, int k) {
3 int[] result = new int[nums.length - k + 1];
4 Deque<Integer> deque = new ArrayDeque<>();
5 for (int i = 0; i < nums.length; i++) {
6 // Remove indices outside current window
7 while (!deque.isEmpty() && deque.peekFirst() < i - k + 1) {
8 deque.pollFirst();
9 }
10 // Remove smaller elements from back
11 while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
12 deque.pollLast();
13 }
14 deque.offerLast(i);
15 // Add max to result when window is complete
16 if (i >= k - 1) {
17 result[i - k + 1] = nums[deque.peekFirst()];
18 }
19 }
20 return result;
21 }
22}1class Solution {
2public:
3 vector<int> maxSlidingWindow(vector<int>& nums, int k) {
4 vector<int> result;
5 deque<int> dq; // stores indices
6 for (int i = 0; i < nums.size(); i++) {
7 // Remove indices outside current window
8 while (!dq.empty() && dq.front() < i - k + 1) {
9 dq.pop_front();
10 }
11 // Remove smaller elements from back
12 while (!dq.empty() && nums[dq.back()] < nums[i]) {
13 dq.pop_back();
14 }
15 dq.push_back(i);
16 // Add max to result when window is complete
17 if (i >= k - 1) {
18 result.push_back(nums[dq.front()]);
19 }
20 }
21 return result;
22 }
23};Time and space complexity
O(n)
Each index is appended once and removed at most once, from either end, so the total work across all iterations is linear even though there are inner while loops.
O(k)
The deque only holds indices inside the current window, so it never has more than k entries. The output list is not counted.
Other approaches
Max-heap with lazy deletion (time O(n log n), space O(n))
Push (negated value, index) pairs into a heap. Before reading the top, pop entries whose index is outside the window. It is easier to come up with but slower than the deque.
Block prefix and suffix maxima (time O(n), space O(n))
Split the array into blocks of size k and precompute the running max from the left and from the right within each block. Each window spans at most two blocks, so its maximum is the larger of one suffix max and one prefix max.
Common mistakes
- Storing values instead of indices in the deque. Without indices you cannot tell when the front has left the window.
- Forgetting the window check on the front of the deque. Popping smaller values from the back does not remove an old maximum, so an index less than
i - k + 1must be dropped from the front before reading it. - Recording results before the first full window, which produces extra entries at the start.
- Using a Python list with
pop(0)for the front, which makes each removal O(n).
Frequently asked questions
Why is the deque solution O(n) when it has nested loops?
Each index enters the deque once and leaves it at most once. Counting across the whole run, the inner loops perform at most n pops in total, so the overall work is linear.
What is a monotonic deque?
It is a double-ended queue whose values stay sorted, here in decreasing order. New elements remove weaker ones from the back, and the front always holds the best candidate.
Can you solve Sliding Window Maximum with a heap?
Yes. Keep a max-heap of values with their indices and discard tops whose index has left the window. That runs in O(n log n), which is usually acceptable, but the deque is optimal.