Skip to main content
General

Monotonic stack - the pattern that blew my mind

Sachin AhujaSachin Ahuja
11 months ago
152

Once I understood monotonic stacks, I couldn't believe how many problems it simplifies:

What it is: A stack that maintains elements in strictly increasing or decreasing order.

Problems it solves:

  • Next Greater Element (the classic)
  • Daily Temperatures
  • Largest Rectangle in Histogram
  • Trapping Rain Water
  • Stock Span Problem
  • Remove K Digits

The template:

stack = []
for i, num in enumerate(arr):
    while stack and condition(stack[-1], num):
        # Process the popped element
        stack.pop()
    stack.append(i)  # or (i, num)

The key insight: elements that will never be needed again get popped immediately, keeping the stack useful.

This pattern is asked in ~5% of all coding interviews. Worth learning!


monotonic-stackpatterntutorialdsa

Comments (1)

Sign in to join the discussion.
Tushar Gupta
Tushar Gupta10 months ago

This monotonic stack pattern really helps with intuitively solving problems like 'Largest Rectangle in Histogram'. I used to struggle with it but now it makes so much sense! Also, do you have any tips on remembering the conditions in the while loop?