Command Palette

Search for a command to run...

← All patterns

Pattern · Stacks & Queues

Monotonic Deque

Keep a deque of candidates in decreasing order so the front is always the max of the current window.

Time O(n) · Space O(k)

Taught in Module 10: Queue, Deque and Monotonic Queue

Think of it like this

A leaderboard that only keeps people who could still be champion: when a stronger player joins, weaker ones behind can never win and are removed.

Clues that point here

  • → Maximum or minimum of every sliding window
  • → DP where you need the max of the last k states

Not this pattern when

  • ✕ The window is the whole array
  • ✕ You need the median (two heaps)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Monotonic Deque · template
Deque<Integer> dq = new ArrayDeque<>();          // indexes, values decreasing
int[] result = new int[nums.length - k + 1];
for (int i = 0; i < nums.length; i++) {
    if (!dq.isEmpty() && dq.peekFirst() <= i - k) dq.pollFirst();      // left the window
    while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]) dq.pollLast();  // can never be max
    dq.offerLast(i);
    if (i >= k - 1) result[i - k + 1] = nums[dq.peekFirst()];
}
return result;

Common versions

  • Sliding window maximum
  • Shortest subarray with sum at least K
  • Constrained subsequence sum

Practice problems with this pattern

Related patterns