Monotonic Queue for Sliding-Window Maximum
Distinguish expired indices from candidates removed because a better value arrived.
Core Intuition & How It Works
A monotonic deque computes the maximum or minimum of every sliding window in O(n) time. It evicts expired indices from the front and pops smaller (dominated) values from the back so the front always holds the window extremum.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n) |
| Space Complexity | O(k) |
| Topic Chapter | Chapter 5: Stacks & Queues |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Perform two O(1) amortized steps per element: drop out-of-window indices at front, drop worse candidates at back, then read front.
Common Pitfalls & Edge Cases
Storing raw values instead of indices, making it impossible to know when the front maximum has slid out of the window.
Real-World & Technical Interview Applications
Sliding-window maximum/minimum, real-time sensor peak tracking, and monotonic-queue DP optimizations.