Sliding Window Maximum
Problem
Given an integer array nums and an integer k, return an array of the maximum values of each sliding window of size k moving from left to right across nums.
- 1 ≤ nums.length ≤ 10⁵
- −10⁴ ≤ nums[i] ≤ 10⁴
- 1 ≤ k ≤ nums.length
Example
nums = [1,3,-1,-3,5,3,6,7], k = 3[3,3,5,5,6,7]The brute-force approach would compute the maximum for each window by scanning all k elements, resulting in O(n*k) time. Instead, the algorithm maintains a deque of indices representing elements in decreasing order of their values. For each new element at index r, it removes indices from the deque's tail whose corresponding values are less than nums[r], ensuring the deque's head always holds the index of the maximum element in the current window. When the left pointer l moves past the deque's head, that index is removed. Once the window size reaches k, the maximum (nums[q[0]]) is appended to the output. This approach achieves O(n) time by ensuring each element is added and removed at most once.
Approach
Straightforward Solution
A naive solution iterates over each window and scans all k elements to find the maximum, resulting in O(n*k) time, which is too slow for large inputs.
Core Observation
The maximum of a sliding window depends on the relative order of elements within that window. Maintaining a data structure that preserves the order of potential maximum candidates allows efficient updates as the window slides.
Path to Optimal
The key recognition signals are 'sliding window', 'maximum in each window', and 'efficient updates'. These indicate the Sliding Window pattern combined with a Monotonic Queue (deque) because it allows constant-time retrieval of the maximum while efficiently discarding obsolete or smaller elements as the window moves.
Optimal Approach
Use a deque to store indices of elements in decreasing order of their values. For each new element, pop from the deque's tail while the current element is greater, ensuring the deque's head is always the maximum. Remove the head if it falls out of the window. Append the maximum to the output once the window size reaches k. This guarantees O(n) time complexity.
Time
O(n)
Each element is added to and removed from the deque at most once, resulting in linear time relative to the input size.
Space
O(k)
The deque stores at most k indices corresponding to elements in the current window, so auxiliary space scales linearly with the window size.
Pattern Spotlight
Sliding Window (Monotonic Queue)
Maintain a deque of indices in decreasing order of their values to ensure the front always holds the maximum for the current window, discarding smaller elements as new ones arrive and removing indices that fall out of the window.
Solution
| 1 | import collections
|
| 2 |
|
| 3 | class Solution:
|
| 4 | def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
|
| 5 | output = []
|
| 6 | q = collections.deque()
|
| 7 | l = r = 0
|
| 8 |
|
| 9 | while r < len(nums):
|
| 10 | while q and nums[q[-1]] < nums[r]:
|
| 11 | q.pop()
|
| 12 | q.append(r)
|
| 13 |
|
| 14 | if l > q[0]:
|
| 15 | q.popleft()
|
| 16 |
|
| 17 | if (r + 1) >= k:
|
| 18 | output.append(nums[q[0]])
|
| 19 | l += 1
|
| 20 | r += 1
|
| 21 |
|
| 22 | return output |
| 1 | import java.util.ArrayDeque; |
| 2 | import java.util.Deque; |
| 3 | |
| 4 | class Solution { |
| 5 | public int[] maxSlidingWindow(int[] nums, int k) { |
| 6 | int[] output = new int[nums.length - k + 1]; |
| 7 | Deque<Integer> q = new ArrayDeque<>(); |
| 8 | int l = 0; |
| 9 | int r = 0; |
| 10 | |
| 11 | while (r < nums.length) { |
| 12 | while (!q.isEmpty() && nums[q.peekLast()] < nums[r]) { |
| 13 | q.pollLast(); |
| 14 | } |
| 15 | q.offerLast(r); |
| 16 | |
| 17 | if (l > q.peekFirst()) { |
| 18 | q.pollFirst(); |
| 19 | } |
| 20 | |
| 21 | if ((r + 1) >= k) { |
| 22 | output[l] = nums[q.peekFirst()]; |
| 23 | l++; |
| 24 | } |
| 25 | r++; |
| 26 | } |
| 27 | |
| 28 | return output; |
| 29 | } |
| 30 | } |
| 1 | #include <vector> |
| 2 | #include <deque> |
| 3 | |
| 4 | using namespace std; |
| 5 | |
| 6 | class Solution { |
| 7 | public: |
| 8 | vector<int> maxSlidingWindow(vector<int>& nums, int k) { |
| 9 | vector<int> output; |
| 10 | deque<int> q; |
| 11 | int l = 0, r = 0; |
| 12 | |
| 13 | while (r < (int)nums.size()) { |
| 14 | while (!q.empty() && nums[q.back()] < nums[r]) { |
| 15 | q.pop_back(); |
| 16 | } |
| 17 | q.push_back(r); |
| 18 | |
| 19 | if (l > q.front()) { |
| 20 | q.pop_front(); |
| 21 | } |
| 22 | |
| 23 | if ((r + 1) >= k) { |
| 24 | output.push_back(nums[q.front()]); |
| 25 | l++; |
| 26 | } |
| 27 | r++; |
| 28 | } |
| 29 | |
| 30 | return output; |
| 31 | } |
| 32 | }; |
| 1 | var maxSlidingWindow = function(nums, k) { |
| 2 | const output = []; |
| 3 | const q = {}; |
| 4 | let front = 0, back = 0; |
| 5 | let l = 0, r = 0; |
| 6 | |
| 7 | while (r < nums.length) { |
| 8 | while (front < back && nums[q[back - 1]] < nums[r]) { |
| 9 | back--; |
| 10 | delete q[back]; |
| 11 | } |
| 12 | q[back] = r; |
| 13 | back++; |
| 14 | |
| 15 | if (l > q[front]) { |
| 16 | delete q[front]; |
| 17 | front++; |
| 18 | } |
| 19 | |
| 20 | if ((r + 1) >= k) { |
| 21 | output.push(nums[q[front]]); |
| 22 | l++; |
| 23 | } |
| 24 | r++; |
| 25 | } |
| 26 | |
| 27 | return output; |
| 28 | }; |
Step-by-Step Solution
Initialize Output List, Deque, and Window Pointers
| 5 | output = []
|
| 6 | q = collections.deque()
|
| 7 | l = r = 0
|
Objective
To prepare data structures and pointers for tracking the sliding window and its maximum efficiently.
Key Insight
Initializing an empty output list collects the maximums for each window. The deque will store indices of elements in decreasing order of their values, enabling O(1) access to the current maximum. Two pointers, l and r, represent the left and right boundaries of the sliding window, facilitating window movement and boundary checks.
Interview Quick-Check
Core Logic
The deque stores indices, not values, to efficiently check if elements are out of the current window and to access their values in nums.
State & Boundaries
Both pointers start at 0, representing an empty window that will expand as r moves forward.
Expand Window and Maintain Monotonic Deque
| 9 | while r < len(nums):
|
| 10 | while q and nums[q[-1]] < nums[r]:
|
| 11 | q.pop()
|
| 12 | q.append(r)
|
Objective
To slide the right pointer forward, updating the deque to maintain decreasing order of values and removing indices of smaller elements.
Key Insight
As the window expands by moving r, the algorithm removes from the deque's tail all indices whose corresponding values are less than nums[r]. This ensures the deque remains sorted in decreasing order, so the front always holds the maximum. This step is crucial to avoid scanning the entire window for the maximum and to maintain O(n) complexity by ensuring each element is processed once.
Interview Quick-Check
Core Logic
Removing smaller elements from the deque's tail before appending the current index ensures the deque's head is always the maximum for the current window.
Common Pitfalls & Bugs
Failing to remove smaller elements leads to incorrect maximums and degrades performance to O(n*k).
Complexity
Each element is pushed and popped at most once, guaranteeing linear time complexity.
Remove Out-of-Window Indices from Deque Head
| 14 | if l > q[0]:
|
| 15 | q.popleft()
|
Objective
To discard indices from the deque's front that are no longer within the current sliding window boundaries.
Key Insight
When the left pointer l moves past the index at the deque's front, that index is removed because it no longer belongs to the current window. This step ensures the deque only contains indices relevant to the current window, maintaining correctness of the maximum retrieval.
Interview Quick-Check
Core Logic
Removing indices outside the window from the deque's front keeps the maximum candidate valid for the current window.
State & Boundaries
The condition l > q[0] checks if the oldest index is out of the window.
Record Maximum and Slide Window Forward
| 17 | if (r + 1) >= k:
|
| 18 | output.append(nums[q[0]])
|
| 19 | l += 1
|
| 20 | r += 1
|
Objective
To append the current window's maximum to the output once the window size reaches k and then move the left pointer to slide the window.
Key Insight
Once the window size is at least k, the maximum element is at the deque's front. Appending nums[q[0]] to output captures this maximum. Incrementing l slides the window forward, preparing for the next maximum calculation. Incrementing r continues expanding the window until the end of the array.
Interview Quick-Check
Core Logic
Appending nums[q[0]] after the window reaches size k ensures the output contains the maximum for each valid window.
State & Boundaries
The condition (r + 1) >= k ensures the window is fully formed before recording maximums.
Common Pitfalls & Bugs
Forgetting to increment l after recording the maximum would cause incorrect window boundaries and output.
Return the List of Sliding Window Maximums
| 22 | return output |
Objective
To output the collected maximum values for all sliding windows after processing the entire array.
Key Insight
Returning the output list completes the algorithm, providing the required maximums for each window in order. This final step is straightforward but essential for correctness.
Interview Quick-Check
Core Logic
Returning the output list delivers the final result of the sliding window maximum computation.
Line Analysis
This solution has 2 Critical lines interviewers watch for.
while q and nums[q[-1]] < nums[r]:
While the deque is not empty and the current element is greater than the element at the deque's tail, pop from the tail.
Removing smaller elements from the tail maintains the deque's decreasing order, ensuring the front always holds the maximum candidate for the current window.
output.append(nums[q[0]])
Append the value at the deque's front index to the output list as the current window's maximum.
The deque's front always holds the index of the maximum element in the current window, so appending nums[q[0]] records the correct maximum.
q = collections.deque()
Create a deque to store indices of elements in decreasing order of their values.
The deque enables O(1) access to the current maximum and efficient updates by maintaining a monotonic decreasing order of values via indices.
if l > q[0]:
Check if the left pointer has moved past the deque's front index.
This condition detects when the maximum candidate at the deque's front is no longer in the current window and must be removed.
q.popleft()
Remove the front index from the deque if it is out of the current window.
Removing outdated indices keeps the deque relevant to the current window, ensuring correctness of the maximum retrieval.
q.pop()
Pop the last index from the deque.
This operation discards indices of elements smaller than the current element, preserving the monotonic property of the deque.
q.append(r)
Append the current index r to the deque.
Adding the current index ensures the deque contains all potential maximum candidates for the current and future windows.
if (r + 1) >= k:
Check if the window size has reached at least k elements.
This condition ensures that maximums are only recorded once the window is fully formed, preventing premature output.
l += 1
Increment the left pointer to slide the window forward.
Moving the left pointer advances the window, preparing for the next maximum calculation and ensuring the window size remains constant.
while r < len(nums):
Start a loop to expand the right pointer until it reaches the end of nums.
This loop iterates over each element, progressively expanding the sliding window and updating the deque accordingly.
r += 1
Increment the right pointer to continue expanding the window.
Advancing the right pointer progresses the iteration through the array, allowing the window to slide across all elements.
l = r = 0
Initialize left and right pointers to zero, representing the sliding window boundaries.
These pointers track the current window's start and end positions, enabling controlled window movement across the array.
return output
Return the list of maximum values for all sliding windows.
This final step outputs the computed maximums, completing the problem's requirement.
output = []
Initialize an empty list to store the maximums of each sliding window.
This list accumulates the results as the window slides, ensuring the final output contains all maximum values in order.
Test Your Understanding
Why does maintaining a deque of indices in decreasing order of their values guarantee O(n) time complexity?
Because each element is pushed and popped at most once from the deque, ensuring that all operations across the entire array sum to O(n), avoiding repeated scanning of elements.
Related Problems
Sliding Window pattern
Don't just read it. Drill it.
Reconstruct Sliding Window Maximum from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Sliding Window Maximum drill