Introduction
The Sliding Window Maximum problem involves finding the maximum element in every window of size k.
Given:
- an array
- window size k
the task is to:
- return maximum element
from every sliding window
This problem is one of the most important applications of:
Monotonic DequeThis problem helps in understanding:
- sliding window technique
- deque operations
- monotonic structures
- efficient range queries
Example
Input:arr = [1,3,-1,-3,5,3,6,7]
k = 3
Output:
[3,3,5,5,6,7]
Explanation:
Window 1:
[1,3,-1]
Maximum:
3
Window 2:
[3,-1,-3]
Maximum:
3
Constraints
1 <= arr.length <= 10^5-10^4 <= arr[i] <= 10^4
1 <= k <= arr.length
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Traverse every window
- Find maximum element
inside current window - Store result
This works but repeated scanning increases complexity.
Steps
- Traverse all windows.
- Scan current window.
- Find maximum value.
- Store result.
- Return answer array.
Dry Run
Input:[1,3,-1,-3,5,3,6,7]
k = 3
Window:
[1,3,-1]
Maximum:
3
Window:
[3,-1,-3]
Maximum:
3
Window:
[-1,-3,5]
Maximum:
5
Final Result:
[3,3,5,5,6,7]
Brute Force Code
Complexity Analysis
Time Complexity: O(n * k)Explanation:
Each window is scanned completely.
Space Complexity: O(1)
Explanation:
Only result storage is used.
Approach 2 : Monotonic Deque
Explanation
The optimized solution uses:
Monotonic Decreasing DequeDeque stores:
- indices of useful elements
Rules:
- Remove smaller elements
from back - Remove out-of-window indices
from front - Front always stores maximum
This gives:
- O(n) solution
Steps
- Create deque.
- Remove smaller elements.
- Remove expired indices.
- Insert current index.
- Store front element as maximum.
Dry Run
Input:[1,3,-1,-3,5,3,6,7]
k = 3
Process 1:
Deque:
[1]
Process 3:
Remove 1
Deque: [3]
Process -1: Deque:
[3,-1]
Window complete
Maximum: 3
Continue traversal...
Final Result: [3,3,5,5,6,7]
Monotonic Deque Code
Complexity Analysis
Time Complexity: O(n)Explanation: Each element enters and leaves deque at most once.
Space Complexity: O(k)
Explanation: Deque stores window indices.