Monotonic Stack Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Monotonic Stack runs in O(n) time and O(n) space, in Python as in every other language.
- ✓The built-in list is the stack: append and pop with no argument are amortised O(1) and there is no separate type to import.
- ✓Store indices, not values, so that i - stack[-1] - 1 gives the width of the span the moment you pop.
- ✓The Python trap: stack[-1] on an empty list raises IndexError rather than returning a sentinel, which is why the and short-circuit is load-bearing rather than stylistic.
- ✓CPython lists over-allocate by roughly one eighth on growth, so append is amortised constant with no reallocation in the common case.
What Monotonic Stack actually is
Monotonic Stack in Python: what you actually reach for
Python implementation
def daily_temperatures(temps: list[int]) -> list[int]:
"""For each day, how many days until a warmer one. O(n) total."""
answer = [0] * len(temps)
stack: list[int] = [] # indices, kept strictly decreasing by temp
for i, t in enumerate(temps):
# "stack and ..." short-circuits: stack[-1] is never evaluated
# on an empty list, where it would raise IndexError.
while stack and temps[stack[-1]] < t:
j = stack.pop() # pop() with no argument is O(1)
answer[j] = i - j # the span falls out of the index
stack.append(i)
return answer
def largest_rectangle(heights: list[int]) -> int:
"""Largest rectangle in a histogram. Each bar is pushed and popped once."""
stack: list[int] = []
best = 0
for i, h in enumerate(heights + [0]): # sentinel flushes the stack
while stack and heights[stack[-1]] >= h:
height = heights[stack.pop()]
left = stack[-1] if stack else -1
best = max(best, height * (i - left - 1))
stack.append(i)
return best
# daily_temperatures([73, 74, 75, 71, 69, 72, 76, 73])
# -> [1, 1, 4, 2, 1, 1, 0, 0]Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Monotonic Stack?
The built-in list is the stack: append and pop with no argument are amortised O(1) and there is no separate type to import. collections.deque works too and is preferable only when you also need the other end.
What is the most common Python mistake when implementing Monotonic Stack?
stack[-1] on an empty list raises IndexError rather than returning a sentinel, which is why the and short-circuit is load-bearing rather than stylistic. The other trap is the one that silently destroys the complexity: list.pop(0) is O(n) because every remaining element shifts down, so code that reaches for it, usually while adapting a queue example, turns the linear algorithm into a quadratic one with no visible change to the logic.
How does Monotonic Stack actually perform in Python?
CPython lists over-allocate by roughly one eighth on growth, so append is amortised constant with no reallocation in the common case. Small integers from -5 to 256 are cached singletons, so pushing indices in that range allocates nothing at all; beyond it each index is a heap-allocated int object. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.