Monotonic Stack
Solve "Next Greater Element" and "Daily Temperatures" problems efficiently! Visualize how maintaining a sorted stack helps find nearest larger/smaller elements in O(n).
Monotonic Stack: Next Greater Element
Find the first larger element to the right for every element in the array.
Initialize empty stack and result array with -1.
Initialize empty stack and result array with -1.
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
Test your knowledge
When should you use a Monotonic Stack?
Write the code
Daily Temperatures
The short version
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.
In more depth
Maintaining Order
A Monotonic Stack is a stack that always stays sorted (increasing or decreasing) from bottom to top. Before pushing a new element, you pop any elements that would violate the chosen order — and those pops are the payoff: each popped element just found its nearest greater or smaller neighbour.
Why O(n) — Amortised Analysis
Each element is pushed exactly once and popped at most once. Total push + pop operations across the entire scan ≤ 2n, so the inner while-loop does not change the overall complexity: it is O(n) amortised. This is the argument interviewers expect you to articulate.
Worked Example (NGE, decreasing stack)
Input: [2, 1, 2, 4, 3]
Final result: [4, 2, 4, -1, -1]
Choosing the Variant
| Goal | Stack order | Pop condition |
|---|---|---|
| Next Greater Element | Decreasing | incoming > top value |
| Next Smaller Element | Increasing | incoming < top value |
| Stock Span | Decreasing | incoming >= top value |
| Previous Greater Element | Decreasing (right-to-left scan) | incoming > top value |
Classic Problem Mapping
When to reach for this
- Find the **Next Greater Element** or **Next Smaller Element**
- Find width of a rectangle in histogram
- Stock span problems
Interview Questions
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required