Courses / DSA Patterns for Working Engineers / Chapter 31
Module 10 · Monotonic stacks, prefix sums and range queries · Chapter 31 of 39
Monotonic Stacks and Deques: Next Greater, Spans and Window Maximums
Builds on Stacks: Matching, Parsing and Nested Structure and Sliding Windows: Fixed and Variable Ranges Over Sequences. Next up: Prefix Sums: Range Totals, Counts and Difference Arrays.
Part 1 · Introduction to monotonic stacks
Waiting for something bigger
A weather station logs one reading a day, and a dashboard wants to know, for each day, how long it took to see a higher one. One pass is enough, if you keep the right kind of stack.
A monotonic stack is an ordinary stack with one extra rule: before an item is pushed, every item on top that would break the sorted order is popped. Between pushes, the items on the stack always stay in order, either never increasing or never decreasing from bottom to top. The order is the "monotonic" part. The pops are where the work happens, and each popped item is one whose question has just been answered.
The classic question is next greater element: for each position i, find the nearest position to its right whose value is strictly larger than a[i], or report that none exists. The answers are positions, with -1 meaning "none". The obvious method scans right from every position until it meets a larger value.
Code blocks follow the convention set out in the first chapter.
// For each index, the index of the next strictly greater value, or -1. export function nextGreaterBrute(a: number[]): number[] { const out: number[] = new Array(a.length).fill(-1) for (let i = 0; i < a.length; i++) { for (let j = i + 1; j < a.length; j++) { if (a[j] > a[i]) { out[i] = j break } } } return out }
ngt.ts: the scan from every position, used as the reference