Sliding Window Maximum
Master this topic with zero to advance depth.
Sliding Window Maximum
Given an array nums and a window size k, return the maximum in each sliding window.
Visual Representation
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Window: [1, 3, -1] Max: 3
Window: [3, -1, -3] Max: 3
Window: [-1, -3, 5] Max: 5
Monotonic Deque (indices):
Step 1 (1): [0]
Step 2 (3): [1] (discarded 0 since 3 > 1)
Step 3 (-1): [1, 2]
Step 4 (-3): [1, 2, 3]
Step 5 (5): [4] (discarded 1, 2, 3 since 5 is larger)Examples
Level I: Brute Force
Intuition
For every possible sliding window of size k, iterate through all its elements to find the maximum value.
Thought Process
- There are
n - k + 1windows in an array of sizen. - For each window starting at index
i, loop fromitoi + k - 1to find the max. - Store the result in an array.
Detailed Dry Run
| Window | Elements | Max | Result |
|---|---|---|---|
| [0, 2] | [1, 3, -1] | 3 | [3] |
| [1, 3] | [3, -1, -3] | 3 | [3, 3] |
| [2, 4] | [-1, -3, 5] | 5 | [3, 3, 5] |
Level II: Heaps / Priority Queue (O(N log N))
Intuition
To find the maximum in a window efficiently, we can use a Max-Heap (Priority Queue). The heap stores pairs of (value, index). For each window, we add the current element to the heap and then remove elements from the top of the heap if their indices are outside the current window.
Thought Process
- Use a Max-Heap to store
[nums[i], i]. - In each step, add the current element to the heap.
- Peek at the top of the heap. If the index is less than
i - k + 1, it's outside the window; remove it (pop). - The top of the heap is the maximum for the current window.
Pattern: Sliding Window + Heap Optimization
Level III: Optimal (Monotonic Deque)
Intuition
Thought Process
We need a way to find the maximum in the current window in . A Monotonic Deque stores indices of elements in strictly decreasing order of their values (nums[dq.front()] is always max).
Logic Steps
- Clean Deque (Old indices): If the index at the front is outside the current window
[i-k+1, i], remove it. - Maintain Monotonicity: Before adding
nums[i], remove all indices from the back whose values are . They can never be the maximum in any future window containingnums[i]. - Add Result: Once the window reaches size
k, the value atnums[dq.front()]is the maximum for the current window.
Detailed Dry Run
| i | Val | Action | Deque (Indices) | Result |
|---|---|---|---|---|
| 1 | 3 | Pop 0 (1 < 3) | [1] | - |
| 2 | -1 | Push 2 | [1, 2] | [3] |
| 3 | -3 | Push 3 | [1, 2, 3] | [3, 3] |
| 4 | 5 | Pop all (all < 5) | [4] | [3, 3, 5] |
⚠️ Common Pitfalls & Tips
Storing values instead of indices in the deque makes it hard to check if the maximum element has slid out of the window. Always store indices.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.