linkjobai / Monotonic Stack: The Pattern Behind "Next Greater Element" Questions
0 лайк(-ов)
0 форк(-ов)
1 файл(-ов)
Последняя активность
Interview prep notes
Monotonic Stack: The Pattern Behind "Next Greater Element" Questions
If a question asks for the next greater, previous smaller, or "how many days until a warmer temperature", a monotonic stack usually turns an O(n²) scan into O(n).
Core idea
Keep a stack of indices whose values are in sorted order (decreasing for "next greater"). When a new value breaks the order, it is the answer for every index you pop.
def daily_temperatures(temps): # LeetCode 739
Новее
Позже