MentorNode
Start free

Pattern 08 of 08 · monotonic-stack

Monotonic Stack & Top-K Heap

Maintain strictly increasing/decreasing stack invariants to resolve next greater/smaller elements or use heaps to maintain streaming top-K items.

Builds on
Two Pointers
Unlocks
The end of this branch.

See the invariant

Step through it
Pattern InvariantMonotonic Stack

Next Greater Element / Daily Temperatures (Days to Warmer Weather)

Step 1 of 12
Temperatures Array:
73°
Day 0ans: 0
74°
Day 1ans: 0
75°
Day 2ans: 0
71°
Day 3ans: 0
69°
Day 4ans: 0
72°
Day 5ans: 0
Monotonic Stack
(Empty Stack)

Initial state: Empty monotonic decreasing stack. Result array initialized to 0s.

Speed:

Practice it

3 problems
  1. 1Daily Temperaturesdaily-temperaturesmedium
  2. 2Largest Rectangle in Histogramlargest-rectangle-in-histogramhard
  3. 3Kth Largest Element in an Array (Min-Heap)kth-largest-element-in-an-arraymedium