Monotonic Queue & Deque DP Optimization: Amortized Linear Time for Sliding Windows

When a recurrence depends on the extremum of previous DP states within a bounded window $[i - K, i - 1]$, maintaining elements in a strictly monotonic deque allows querying the window extremum in $O(1)$ amortized time.

1. Monotonic Queue Invariants

  • Front Element: Always holds the optimal DP value for the current window.
  • Monotonic Ordering: Elements in the deque are maintained in strictly decreasing (or increasing) value order.
  • Out-of-Window Eviction: Elements whose indices fall below $i - K$ are popped from the front.

Ready to Master LeetCode Hard Patterns?

Get instant lifetime access to all 45 video lectures, interactive source code templates, and interview prep guides.

Enroll in Masterclass ($49)

Disclaimer: LeetCode is a registered trademark of LeetCode LLC. Our tutorials are independent educational guides developed by industry veterans and are not affiliated with LeetCode.