Sliding Window Maximum - Problem
Imagine you're looking through a sliding window that moves across an array of integers from left to right. Your task is to find the maximum value visible through this window at each position.
Given an array
Goal: Return an array containing the maximum value for each window position.
Example: For array
• Window [1,3,-1] → max = 3
• Window [3,-1,-3] → max = 3
• Window [-1,-3,5] → max = 5
• And so on...
Given an array
nums and a window size k, the window starts at the leftmost position and slides one position to the right each time until it reaches the end. At each position, you need to identify the largest number currently visible in the window.Goal: Return an array containing the maximum value for each window position.
Example: For array
[1,3,-1,-3,5,3,6,7] with window size k=3:• Window [1,3,-1] → max = 3
• Window [3,-1,-3] → max = 3
• Window [-1,-3,5] → max = 5
• And so on...
Input & Output
example_1.py — Basic sliding window
$
Input:
nums = [1,3,-1,-3,5,3,6,7], k = 3
›
Output:
[3,3,5,5,6,7]
💡 Note:
Window [1,3,-1] max=3, [3,-1,-3] max=3, [-1,-3,5] max=5, [-3,5,3] max=5, [5,3,6] max=6, [3,6,7] max=7
example_2.py — Single element window
$
Input:
nums = [1], k = 1
›
Output:
[1]
💡 Note:
With window size 1, each element is the maximum of its own window
example_3.py — Window equals array size
$
Input:
nums = [9,10,9,-7,-4,-8,2,-6], k = 8
›
Output:
[10]
💡 Note:
Single window covering entire array, maximum element is 10
Visualization
Tap to expand
Understanding the Visualization
1
Camera Setup
Position camera to view first k rooms in the corridor
2
Smart Monitoring
AI system maintains list of rooms with highest threat levels
3
Camera Slides
As camera moves, system automatically removes rooms no longer in view
4
Update Threats
New room enters view, system discards lower threats that can't be maximum
5
Report Maximum
System instantly reports highest current threat without scanning all rooms
Key Takeaway
🎯 Key Insight: Like a smart security system, the monotonic deque eliminates impossible candidates proactively, ensuring we can always find the maximum threat level instantly without rescanning all zones.
Time & Space Complexity
Time Complexity
O(n)
Each element is added and removed from deque at most once, resulting in linear time
✓ Linear Growth
Space Complexity
O(k)
Deque stores at most k indices for the current window
✓ Linear Space
Constraints
- 1 ≤ nums.length ≤ 105
- -104 ≤ nums[i] ≤ 104
- 1 ≤ k ≤ nums.length
- The sliding window moves from left to right exactly one position at a time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code