AlgoTales · Roadmap

Monotonic queue

Advanced · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A monotonic queue is a queue that is kept in order, for example from biggest to smallest, by throwing out items that can never be the answer again. The front always holds the best item for the current window, found without searching.

Practical use cases

  • Web app: Highest temperature in the last hour. A monitoring page shows the peak server temperature over the last 60 minutes, updated every minute. Rescanning 60 readings each time is wasteful when there are hundreds of servers. A monotonic queue keeps only readings that could still be the peak, so the maximum is read from the front.
  • Web app: Best sales day in a moving 7-day window. An analytics screen shows, for every day, the top sales figure of the past week. A queue drops smaller old figures whenever a bigger new one arrives. Each day then reads the answer from the front, so a year of data is processed in a single pass.
  • System: Streaming data and speed-ups. Sensor and trading systems that must report a rolling high or low from a never-ending stream use this queue to keep up. It is also a handy trick whenever a calculation needs the best value from a recent range of earlier results.

The story: The Class Photo Line

Before the annual-day photo, Mrs. Sharma lined up her students from the gate. Students kept joining at the back and, one by one, the front ones went to the stage. Between all this, the photographer kept shouting: "Who is the tallest in the line right now? I need to decide where to place the tripod!"

Aarav, the monitor, first walked along the whole line every single time to find the tallest. With forty students and the question asked after every move, he was exhausted. Zoya had a cleverer thought: "When a tall student joins at the back, every shorter student standing in front is useless for this question. The tall one is taller, and will leave the line later than them. So the shorter ones can never be the tallest again!"

So Zoya kept a second, short list: tall students only, in decreasing order of height. A newcomer sends away every shorter student at the back of that list, then joins. The front of the list is always the tallest, and when the real line's front student leaves, you only remove them from the list if they are at its front too. A list that always stays in one direction (here, decreasing) is called monotonic, and with a queue it becomes a monotonic queue.

How to spot this problem, and where you need it

You need the biggest or smallest value among the most recent few items, repeatedly as the window slides, and recalculating it from scratch for each step is too slow.

Signs you need it

  • The task says "maximum in every window of size k", "rolling high", "highest in the last N minutes" or "lowest in the last 7 days".
  • You call max() or min() on a slice of an array for each position, and the cost grows with the window size.
  • Old values fall out of the window while new ones arrive, and you need the best one at every step.

Where to use it in a project

  • Monitoring dashboards with rolling highs and lows over servers, sensors and prices.
  • Analytics screens with moving-window statistics on daily or hourly figures.
  • Optimisation code that needs the best value within a recent range.

The solution

Keep a queue of positions whose values are in decreasing order. When a new value arrives, remove from the back every value smaller than it, since they can never be the maximum again, then add the new one at the back. Remove from the front any position that has left the window. The front is always the current maximum.

Payoff: Before: scanning 60 readings for each of 10,000 steps. After: each reading is added and removed at most once, about 20,000 steps in total.

Explain it like I am 8

Imagine a line of kids where a new, taller kid walks up and says to the shorter kids ahead of them: "You will never be the tallest while I am here." Those shorter kids are asked to step out of the list. In the end, the kid at the front of your list is always the tallest.

How it works, step by step

  1. Keep a deque (a double-ended queue) of values, kept in decreasing order from front to back.
  2. Push x: while the last value in the deque is smaller than x, remove it from the back. Then add x at the back.
  3. Max: the front of the deque is the biggest value in the line. Just read it.
  4. Pop x (the oldest leaves the real queue): if the deque's front equals x, remove it from the front. Otherwise do nothing, since it was already discarded.
  5. Each value enters the deque once and leaves once, so the work is tiny even though a push may remove many values.

The code in four languages

PHP

<?php
// A queue that can report its maximum in O(1).
class MaxQueue {
    private array $dq = [];   // values kept in decreasing order
    private int $head = 0;    // front of the deque (we move this instead of shifting)

    public function push(int $x): void {
        // throw away smaller values at the back; they can never be the maximum again
        while (count($this->dq) > $this->head && end($this->dq) < $x) array_pop($this->dq);
        $this->dq[] = $x;
    }
    // call this with the value that is leaving the real queue
    public function pop(int $x): void {
        if (count($this->dq) > $this->head && $this->dq[$this->head] === $x) $this->head++;
    }
    public function max(): ?int {
        return count($this->dq) > $this->head ? $this->dq[$this->head] : null;
    }
}

$mq = new MaxQueue();
foreach ([3, 1, 4] as $x) $mq->push($x);
echo "max: " . $mq->max() . "\n";    // 4
$mq->pop(3);                          // 3 leaves the line, it was not the tallest
echo "max: " . $mq->max() . "\n";    // 4
$mq->push(1); $mq->push(5);
echo "max: " . $mq->max() . "\n";    // 5
$mq->pop(1); $mq->pop(4); $mq->pop(1);
echo "max: " . $mq->max() . "\n";    // 5 (still in line)
$mq->pop(5);
echo "max: " . var_export($mq->max(), true) . "\n";   // NULL, the helper is empty

JavaScript

// A queue that can report its maximum in O(1).
class MaxQueue {
  constructor() {
    this.dq = [];     // values kept in decreasing order
    this.head = 0;    // front of the deque (we move this instead of shifting)
  }
  push(x) {
    // throw away smaller values at the back; they can never be the maximum again
    while (this.dq.length > this.head && this.dq[this.dq.length - 1] < x) this.dq.pop();
    this.dq.push(x);
  }
  // call this with the value that is leaving the real queue
  pop(x) {
    if (this.dq.length > this.head && this.dq[this.head] === x) this.head++;
  }
  max() {
    return this.dq.length > this.head ? this.dq[this.head] : null;
  }
}

const mq = new MaxQueue();
for (const x of [3, 1, 4]) mq.push(x);
console.log('max: ' + mq.max());    // 4
mq.pop(3);                           // 3 leaves the line, it was not the tallest
console.log('max: ' + mq.max());    // 4
mq.push(1); mq.push(5);
console.log('max: ' + mq.max());    // 5
mq.pop(1); mq.pop(4); mq.pop(1);
console.log('max: ' + mq.max());    // 5 (still in line)
mq.pop(5);
console.log('max: ' + mq.max());    // null, the helper is empty

Java

import java.util.*;

public class Main {
    // A queue that can report its maximum in O(1).
    static class MaxQueue {
        private final Deque<Integer> dq = new ArrayDeque<>();   // values kept in decreasing order

        void push(int x) {
            // throw away smaller values at the back; they can never be the maximum again
            while (!dq.isEmpty() && dq.peekLast() < x) dq.pollLast();
            dq.addLast(x);
        }

        // call this with the value that is leaving the real queue
        void pop(int x) {
            if (!dq.isEmpty() && dq.peekFirst() == x) dq.pollFirst();
        }

        Integer max() {
            return dq.isEmpty() ? null : dq.peekFirst();
        }
    }

    public static void main(String[] args) {
        MaxQueue mq = new MaxQueue();
        for (int x : new int[]{3, 1, 4}) mq.push(x);
        System.out.println("max: " + mq.max());    // 4
        mq.pop(3);                                 // 3 leaves the line, it was not the tallest
        System.out.println("max: " + mq.max());    // 4
        mq.push(1); mq.push(5);
        System.out.println("max: " + mq.max());    // 5
        mq.pop(1); mq.pop(4); mq.pop(1);
        System.out.println("max: " + mq.max());    // 5 (still in line)
        mq.pop(5);
        System.out.println("max: " + mq.max());    // null, the helper is empty
    }
}

Go

package main

import "fmt"

// MaxQueue is a queue that can report its maximum in O(1).
type MaxQueue struct {
	dq   []int // values kept in decreasing order
	head int   // front of the deque (we move this instead of re-slicing)
}

func (m *MaxQueue) Push(x int) {
	// throw away smaller values at the back; they can never be the maximum again
	for len(m.dq) > m.head && m.dq[len(m.dq)-1] < x {
		m.dq = m.dq[:len(m.dq)-1]
	}
	m.dq = append(m.dq, x)
}

// Pop is called with the value that is leaving the real queue.
func (m *MaxQueue) Pop(x int) {
	if len(m.dq) > m.head && m.dq[m.head] == x {
		m.head++
	}
}

func (m *MaxQueue) Max() (int, bool) {
	if len(m.dq) > m.head {
		return m.dq[m.head], true
	}
	return 0, false
}

func show(m *MaxQueue) {
	if v, ok := m.Max(); ok {
		fmt.Println("max:", v)
	} else {
		fmt.Println("max: null") // the helper is empty
	}
}

func main() {
	mq := &MaxQueue{}
	for _, x := range []int{3, 1, 4} {
		mq.Push(x)
	}
	show(mq)  // 4
	mq.Pop(3) // 3 leaves the line, it was not the tallest
	show(mq)  // 4
	mq.Push(1)
	mq.Push(5)
	show(mq) // 5
	mq.Pop(1)
	mq.Pop(4)
	mq.Pop(1)
	show(mq) // 5 (still in line)
	mq.Pop(5)
	show(mq) // null, the helper is empty
}

Time: O(1) amortized · Extra space: O(n). One push can remove many values, but each value is removed at most once, so the average cost per operation stays constant.

Watch out for

  • Removing values when they are equal to the new one by accident. Decide on < or <= and be careful with duplicates when popping by value (storing indexes is safer).
  • Calling pop(x) and removing from the helper unconditionally. Only remove if the helper's front is the leaving item.
  • Calling it "O(n) per push" because of the inner while loop. Count the total work, not the worst single push.

Quick check

  1. In a max-monotonic queue, in what order are values kept from front to back?
    • Increasing
    • Random
    • Decreasing
  2. A new value arrives. What happens to smaller values at the back of the helper?
    • They are removed from the back
    • They stay forever
    • They move to the front
  3. The real queue removes a value that is NOT at the helper's front. What does the helper do?
    • Remove its front
    • Nothing
    • Rebuild itself