The monotonic stack template

Video lessonComing soon

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.

42looks13finds625
Heights at indexes 0 to 6. The 2 at index 1 looks past the 1 and finds the 3

The 6 at index 4 finds nobody taller, so its answer is −1. For the whole row, the answers are:

60313263-1455-16
answer: the first taller height to the right of each index

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.

Next greater, one newcomer at a time
4i213625
0: 4top →
stack
0123456
i = 0: nobody waits yet, so 4 waits

The same run as a table. Each popped index gets nums[i] as its answer, and the stack column lists indexes, bottom first:

inums[i]poppedstack after
04none0
12none0, 1
21none0, 1, 2
332, 10, 3
463, 04
52none4, 5
6554, 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:

FindStack, bottom to topPop while nums[top] isAnswer
Next greatergoes down< nums[i]each popped index gets nums[i]
Next smallergoes up> nums[i]each popped index gets nums[i]
Previous greatergoes down<= nums[i]i gets the top, before the push
Previous smallergoes 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.

4213625i
Before index 6, only the 6 and the 2 can be seen. The 6 hides everyone before it

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.

4213625
The 2 at index 5 spreads over indexes 3 to 6. Its area is 2 × 4 = 8

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].
  • if instead of while. 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.

Before writing a loop inside a loop that looks for the next bigger or smaller value, ask who is still waiting for an answer, and keep them on a stack.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.