Preview — Pro guide
You are seeing a portion of this guide. Sign in and upgrade to unlock the full article, quizzes, and interview answers.
Monotonic Stack and Deque: Next Greater Element in O(n)
The single most underused O(n) pattern in coding interviews. Learn exactly when to use a monotonic stack vs. deque, why storing indices beats storing values, and how to solve histogram rectangle and sliding window maximum problems that stump most candidates.
The O(n) Insight Most Candidates Miss
The brute force for 'find the next greater element for every element in an array' is O(n²): for each element, scan right until you find something larger. Most candidates reaching for this problem at a FAANG interview write exactly that — and then get asked to optimize it. The O(n) solution uses a monotonic stack, and the key insight is deceptively simple: each element is pushed and popped at most once, giving O(n) total operations across all n iterations of the outer loop.
The mechanism: maintain a stack of 'pending' elements — elements that have not yet found their next greater element. When you encounter a new element num, if it is larger than the top of the stack, then num is the next greater element for the stack top. Pop it, record the answer, and repeat while the new element is still larger than the current top. Then push the new element as a new pending candidate. Elements that remain on the stack after the full traversal have no next greater element — their answer is -1.
This pattern generalizes to six closely related problem types: next greater, next smaller, previous greater, previous smaller (by reversing traversal or reversing the comparison), and two range problems — largest rectangle in histogram and sliding window maximum — that require the same stack/deque discipline. Recognizing that these six problems all reduce to the same core operation is what separates candidates who internalize the pattern from those who memorize solutions.
What Interviewers Are Testing
Two probes distinguish strong candidates: (1) Why store indices instead of values? The answer is that indices let you compute distances between elements (days gap in LC 739, width of histogram bar in LC 84) — values alone cannot recover this spatial information. (2) Why is the overall algorithm O(n) despite the inner while loop? Same amortized argument as sliding window — each element is pushed once and popped at most once, so the total number of pop operations across all n iterations is at most n. The inner while loop does not add an O(n) factor; it redistributes work that is bounded globally.