Monotonic queue
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A monotonic queue keeps only the candidates that could still become the maximum (or minimum) of a moving window, throwing away weaker ones as soon as a stronger one arrives. It gives the biggest value in every window in one pass.
Practical use cases
- Web app: Highest temperature in each 10-minute window. A monitoring dashboard displays the maximum reading in every rolling 10-minute window from sensor data. Re-scanning 600 readings per update is wasteful. The queue holds only readings that could still be the maximum, so the front is the answer each time, and each reading is added and removed only once.
- Web app: Peak traffic in the last hour. An analytics page shows the highest requests-per-minute value of the past 60 minutes, updating each minute. The queue keeps it current with one push and a few pops.
- Web app: Best price seen in the last N days. A price-tracker highlights the lowest price in the last 30 days next to each date. A minimum queue gives every date's answer in one pass over the data.
- System: Video analytics and constrained planning. Video tools find the brightest moment within a moving time frame, and planners use the same queue to speed up decisions limited to the last few steps. Tools stay responsive even on long recordings, since each frame joins and leaves the queue once.
The story: The Cricket Hall of Fame Window
Aarav ran the scoreboard for a school cricket league. After every ball, the sports teacher asked: "Who has the highest score among the last 3 matches?" With each new match, the oldest match drops out of view and a new one comes in. Aarav re-read all three scores every time. For a whole season (hundreds of matches), his eyes burned.
Mira spotted the smell: "maximum in every window of size k". That is a window problem, but a plain sliding-window sum will not do, because when the top score leaves, we do not know the next best without looking again. We need a smarter list.
Her idea: keep a short queue of candidates only. When a new score arrives, every weaker score at the back of the queue can never be champion again: the new score is higher and will stay in the window longer. Kick them out! Also, if the front score is too old to be in the window, remove it. The score at the front is always the champion.
This queue is kept in order, with scores going down from front to back, so it is called a monotonic queue (or monotonic deque). It gives each window's maximum with one glance.
How to spot this problem, and where you need it
You need the maximum or minimum of a moving window over a stream or list, and recalculating it from every item in the window at each step is slow.
Signs you need it
- The wording is "maximum in each window of size k", "rolling max", or "peak in the last N minutes".
- Your loop calls max() on a slice for every position, repeating most of the same work.
- Older values that are smaller than a newer one can never matter again.
Where to use it in a project
- Live monitoring charts that show rolling peaks or lows over the last few minutes.
- Price and metric trackers that highlight the best value in a recent period.
- Planning steps that depend only on a recent window of earlier results.
The solution
Keep a double-ended queue of positions whose values are in decreasing order. When a new value arrives, remove from the back every value smaller than it, then add it at the back. Remove from the front any position that has slid out of the window. The front of the queue is always the current maximum. Each item enters and leaves once.
Payoff: Before: 600 comparisons per update. After: about 2 queue operations per update.
Explain it like I am 8
A queue of boxers where only the strongest stay. When a new boxer arrives, he sends every weaker boxer in the back home, because they can never beat him. When the front boxer gets too old for the tournament, he retires. The front boxer is always the champion.
How it works, step by step
- Clues: "maximum/minimum in every window of size k", "sliding window maximum", "shortest subarray with sum at least k". Think monotonic queue.
- Keep a deque of indexes whose values go down from front to back.
- For the new element, pop from the back while the back value is
<=the new one. Then push the new index at the back. - Drop the front if its index has slid out of the window (
front <= i - k). - Once the first window is full, the front of the deque is the window's maximum. Record it and keep going.
The code in four languages
PHP
<?php
// Sliding Window Maximum using a monotonic deque of indexes
function windowMax(array $a, int $k): array {
$dq = new SplDoublyLinkedList(); // indexes, values decreasing front -> back
$out = [];
for ($i = 0; $i < count($a); $i++) {
// Weaker candidates at the back can never be champion again.
while (!$dq->isEmpty() && $a[$dq->top()] <= $a[$i]) {
$dq->pop();
}
$dq->push($i);
// Front too old for the window? Remove it.
if ($dq->bottom() <= $i - $k) {
$dq->shift();
}
if ($i >= $k - 1) {
$out[] = $a[$dq->bottom()]; // front is the champion
}
}
return $out;
}
echo implode(", ", windowMax([1, 3, -1, -3, 5, 3, 6, 7], 3)); // 3, 3, 5, 5, 6, 7JavaScript
// Sliding Window Maximum using a monotonic deque of indexes
function windowMax(a, k) {
const dq = []; // indexes, values decreasing front -> back (shift is fine for a demo)
const out = [];
for (let i = 0; i < a.length; i++) {
// Weaker candidates at the back can never be champion again.
while (dq.length && a[dq[dq.length - 1]] <= a[i]) {
dq.pop();
}
dq.push(i);
// Front too old for the window? Remove it.
if (dq[0] <= i - k) {
dq.shift();
}
if (i >= k - 1) {
out.push(a[dq[0]]); // front is the champion
}
}
return out;
}
console.log(windowMax([1, 3, -1, -3, 5, 3, 6, 7], 3).join(", ")); // 3, 3, 5, 5, 6, 7Java
import java.util.*;
public class Main {
// Sliding Window Maximum using a monotonic deque of indexes
static int[] windowMax(int[] a, int k) {
Deque<Integer> dq = new ArrayDeque<>(); // indexes, values decreasing front -> back
int[] out = new int[a.length - k + 1];
for (int i = 0; i < a.length; i++) {
// Weaker candidates at the back can never be champion again.
while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) {
dq.pollLast();
}
dq.addLast(i);
// Front too old for the window? Remove it.
if (dq.peekFirst() <= i - k) {
dq.pollFirst();
}
if (i >= k - 1) {
out[i - k + 1] = a[dq.peekFirst()]; // front is the champion
}
}
return out;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(windowMax(new int[]{1, 3, -1, -3, 5, 3, 6, 7}, 3)));
// [3, 3, 5, 5, 6, 7]
}
}Go
package main
import "fmt"
// windowMax is Sliding Window Maximum using a monotonic deque of indexes.
func windowMax(a []int, k int) []int {
var dq []int // indexes, values decreasing front -> back
var out []int
for i := range a {
// Weaker candidates at the back can never be champion again.
for len(dq) > 0 && a[dq[len(dq)-1]] <= a[i] {
dq = dq[:len(dq)-1]
}
dq = append(dq, i)
// Front too old for the window? Remove it.
if dq[0] <= i-k {
dq = dq[1:]
}
if i >= k-1 {
out = append(out, a[dq[0]]) // front is the champion
}
}
return out
}
func main() {
fmt.Println(windowMax([]int{1, 3, -1, -3, 5, 3, 6, 7}, 3))
// [3 3 5 5 6 7]
}Time: O(n) · Extra space: O(k). Each index enters and leaves the deque once; the deque never holds more than k indexes.
Watch out for
- Storing values instead of indexes, so you cannot tell when the front has slid out of the window.
- Using a plain max over each window, which is O(n × k).
- Popping from the back with
<and not<=: equal older scores just waste space (they leave sooner), so remove them.
Quick check
- Which problem statement suggests a monotonic queue?
- "Highest value in every window of size k"
- "Count distinct words"
- "Reverse a string"
- Why can a weaker score at the back be removed when a bigger score arrives?
- It is not in the window
- The array is sorted
- The new score is bigger and stays in the window longer
- Where is the current window's maximum?
- At the back of the deque
- At the front of the deque
- In the middle