The monotonic stack template
1 The first taller person to the right
Seven people stand in a row, all facing right. Each one wants to know the first person to their right who is taller.
The 6 at index 4 finds nobody taller, so its answer is −1. For the whole row, the answers are:
This is the next greater element of each index. The direct way lets each person look right until someone is taller. On a row that only gets shorter, nobody finds anyone, and each person looks at everyone after them. At n = 10⁵, that is around 5 × 10⁹ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
The looks repeat. The 2 at index 1 looks past the 1 to the 3, and then the 1 looks at the same 3 again. One pass can answer everyone, if we keep track of who is still waiting.
2 Who is still waiting
We walk the row from left to right. A person is waiting until someone taller comes after them. Two facts make the walk fast:
- A newcomer answers every waiting person who is shorter. Nobody between them was taller, or the wait would have ended already. So the newcomer is their first taller person.
- The waiting people get shorter from left to right. If a short person waited to the left of a taller one, the taller one would have ended that wait on arrival.
So the shortest waiting person is always the most recent. A newcomer ends waits from the most recent backwards, and stops at the first person who is at least as tall. The last one in is the first one out, so the waiting people sit on a stack.
From bottom to top, the heights on this stack always go down. A stack kept in one order like this is a monotonic stack. The template is three lines:
for each index i, from left to right:
while the stack is not empty and nums[top] < nums[i]:
answer[top] = nums[i], then pop
push i
People still on the stack at the end never met anyone taller. Their answer is −1.
3 Watching the stack
Here is the run on our row. The blue bars are the people waiting on the stack. Each stack entry is written as index: height, and orange marks an answer just written.
The same run as a table. Each popped index gets nums[i] as its answer, and the stack column lists indexes, bottom first:
| i | nums[i] | popped | stack after |
|---|---|---|---|
| 0 | 4 | none | 0 |
| 1 | 2 | none | 0, 1 |
| 2 | 1 | none | 0, 1, 2 |
| 3 | 3 | 2, 1 | 0, 3 |
| 4 | 6 | 3, 0 | 4 |
| 5 | 2 | none | 4, 5 |
| 6 | 5 | 5 | 4, 6 |
As heights, the stack column always goes down: 4, 2, 1, then 4, 3, then 6, 5. The pops come off the top, from the most recent person backwards.
4 The code and its cost
The stack holds indexes, not heights. An index says where to write the answer, and nums[index] still gives the height. The answer array starts at −1, so the people left on the stack need no extra loop.
On our row, every tab returns [6, 3, 3, 6, -1, 5, -1]. Only the spelling of push, top and pop changes between languages.
The cost. A while inside a for looks like n² work. But each index is pushed once and popped at most once, so the whole pass makes at most 2n stack operations. That is O(n), even though one step can pop many. This count over the whole run is the amortised cost. At n = 10⁵, that is around 2 × 10⁵ steps instead of 5 × 10⁹.
A row that only gets shorter keeps every index on the stack, so the extra space is O(n).
5 Four variants of one loop
The same loop finds four things. Only the comparison changes, and when the answer is written:
| Find | Stack, bottom to top | Pop while nums[top] is | Answer |
|---|---|---|---|
| Next greater | goes down | < nums[i] | each popped index gets nums[i] |
| Next smaller | goes up | > nums[i] | each popped index gets nums[i] |
| Previous greater | goes down | <= nums[i] | i gets the top, before the push |
| Previous smaller | goes up | >= nums[i] | i gets the top, before the push |
For a previous question, each person looks left. A person standing behind someone taller is hidden from everyone further right. So for previous greater, the stack holds the people who can still be seen. A newcomer pops everyone they hide. The top is then the first taller person to the left, and an empty stack means −1.
The 5 at index 6 pops the 2, and the top is the 6. So its previous greater is 6. For the whole row, the previous greater values are [-1, 4, 2, 4, -1, 6, 6].
The ties differ for a reason. A next variant pops the people the newcomer answers, and a person of equal height is not taller. A previous variant pops the people the newcomer hides, and someone of equal height is hidden too.
6 Distances and circular arrays
Because the stack holds indexes, it also gives distances. Daily Temperatures asks how many days each day waits for a warmer one. The answer array starts at 0, and one line changes:
answer[top] = i - top
Our row, read as temperatures, gives [4, 2, 1, 1, 0, 1, 0].
In Next Greater Element II, the row stands in a circle. After the last person, the looking goes on from the first. On our row, the 5 at index 6 now looks round past 4, 2, 1 and 3, and finds the 6.
We do not copy the array. We walk it twice, for i from 0 to 2n − 1, and use index i mod n. The second lap only answers people who are still waiting, so it pushes nothing:
for i from 0 to 2n − 1:
j = i mod n
while the stack is not empty and nums[top] < nums[j]:
answer[top] = nums[j], then pop
if i < n:
push j
The answers become [6, 3, 3, 6, -1, 5, 6]. The 6 still gets −1, because nobody in the circle is taller. Two laps are still O(n).
7 Spans and equal values
Some problems need both sides of each index. Largest Rectangle in Histogram asks for the biggest rectangle under the bars. A rectangle as high as one bar spreads left and right until it meets a shorter bar. So its edges are that bar's previous smaller and next smaller.
The 2 at index 5 has its previous smaller at index 2 and none to its right, so its next is n = 7. Its width is next − previous − 1 = 7 − 2 − 1 = 4. One pass per side gives every bar's span in O(n), and the largest area, 8 here, is the answer.
Sum of Subarray Minimums uses the same spans, to count the subarrays where each value is the minimum. Ties need care there. In [2, 2], both 2s are the minimum of [2, 2]. If both sides stop only at a strictly smaller value, both 2s claim it, and it is counted twice. So the left side stops at a smaller or equal value, and the right only at a strictly smaller one. Then [2, 2] belongs to the first 2 alone.
8 Mistakes, and when to use it
- Comparing an index with a height.
waiting.top() < nums[i]compares index 0 with the height 2. On[4, 2], it pops the 4 and gives[2, -1]instead of[-1, -1]. ifinstead ofwhile. Each newcomer pops at most one person. On[4, 2, 1, 3], the 3 answers the 1 but leaves the 2 waiting, so the 2 gets −1 instead of 3.- The wrong direction.
>finds the next smaller instead. On[1, 3], it gives[-1, -1]instead of[3, -1]. - A tie that pops.
<=in next greater treats an equal height as taller. On[3, 3], it gives[3, -1]instead of[-1, -1]. - Forgetting the leftovers. Indexes still on the stack are never written. Start the answer array at what "no answer" means in the problem: −1 for a value, 0 days in Daily Temperatures, or n for a span's right edge.
The sign is a question about each element's next or previous element that is larger or smaller. It comes in a few shapes:
- The value, index or distance itself. Next Greater Element I, Daily Temperatures and Next smaller element.
- A span back to the previous greater. Online Stock Span counts the days back to the last higher price.
- Spans on both sides. Largest Rectangle in Histogram, Sum of Subarray Minimums, and Sum of Subarray Ranges, which also needs the maximums.
- Keeping the smallest result. Remove K Digits keeps the digits in an increasing stack, and pops a bigger digit when a smaller one arrives, while it may still remove digits.
The Monotonic queue problems next keep the same order, but in a queue. Old indexes then also leave from the front as a window slides.
Practice it
- Next Greater Element IEasy
- Daily TemperaturesMedium
- Next Greater Element IIMedium
- Online Stock SpanMedium
- Car FleetMedium
- Remove K DigitsMedium
- Sum of Subarray MinimumsMedium
- Sum of Subarray RangesMedium
- Largest Rectangle in HistogramHard
- Maximal RectangleHard
- Next smaller elementMedium
- Number of greater elements to the rightMedium
- 132 PatternMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.