Module 5 · Stacks, Queues and Linked Lists · Lesson 15 of 40
Monotonic stack: the next greater number
Keep a stack in order to answer 'what is the next bigger value?' for every item in one pass.
In this lesson · about 18 minutes
- Explain what a monotonic stack keeps
- Find the next greater element for every item in O(n)
- Recognise 'next bigger / next smaller' questions
Here is a common question: for each day's temperature, how many days until a warmer day? Or: for each number, what is the next greater number to its right?
The slow way looks to the right of every item: O(n²). The smart way uses a monotonic stack, a stack whose items are always in order (here, from big at the bottom to small at the top).
How it works
Walk left to right. The stack holds the indexes of items still waiting for their "next greater".
- When a new number arrives, it is the answer for every waiting item that is smaller than it. Pop those and record the new number as their answer.
- Then push the new number's index: now it waits too.
- Anything still waiting at the end has no greater number: answer -1.
Every index is pushed once and popped at most once, so the whole thing is O(n).
nums = [2, 1, 2, 4, 3]
answer = [4, 2, 4, -1, -1]
Flip the comparison to find the next smaller value. Walk right to left to find the previous greater or smaller value. The same idea solves the "stock span" problem.
Try it: watch the stack
Exercise
Next greater element
Write next_greater(nums) that returns a list where each item is the next bigger number to its right, or -1 if there is none.
Check your understanding0 of 2 correct
Quiz score: 0 of 2
Exercises solved: 0 of 1
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.