Monotonic Stack
Find the next or previous greater or smaller element for every position in one O(n) pass, with a stack that stays sorted from bottom to top.
Overview
The idea
Many problems ask, for every element of an array, where the nearest larger (or smaller) element is. Checking each element against everything to its right costs O(n²). A monotonic stack answers every position in one pass.
The stack holds indexes whose values are sorted from bottom to top ('monotonic' means always moving in one direction). Each index on it is still waiting for its answer. When a new element arrives, it is compared with the top. Every top it beats is popped, and the new element is that popped index's answer. Then the new index is pushed. Because an index is pushed once and popped at most once, the whole pass is O(n).
The gap is large in practice. Take n = 100,000. Scanning right from each element until a larger one appears can take up to about 5 billion comparisons, since n(n − 1) ÷ 2 = 4,999,950,000, roughly n² ÷ 2. That is O(n²). The monotonic stack does at most about 200,000 operations, one push and one pop per index, since 2n = 200,000. That is O(n).
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio