Monotonic Stack
6 min read.
Solve "Next Greater Element" and "Daily Temperatures" problems efficiently! Visualize how maintaining a sorted stack helps find nearest larger/smaller elements in O(n).
Think of it this way: Think of looking for a view in a city skyline. If a taller building is in front of you, it blocks your view of smaller buildings behind it. You only see the 'next greater' building.
Scan left to right. The stack holds indices still waiting for a bigger value to their right.
Check your understanding
Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.
Next greater element
Order what the algorithm does for each element, scanning left to right.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Quiz
20 questionsWhen should you use a Monotonic Stack?
Done with this lesson?
Sign in free to keep your progress, streak and quiz scores.