Skip to main content
Monotonic StackStackPatternsArrays

Monotonic Stack — Complete Guide With LeetCode Problems [2026]

· 9 min read

Syed Peera Saheb

Software Engineer · 5+ years in tech interviews

Summary

Monotonic stacks solve next-greater-element and histogram problems in O(n). The pattern, both variants, and the 6 problems that appear in real interviews.

What makes a stack monotonic

A regular stack pushes and pops in LIFO order with no constraints on element ordering. A monotonic stack adds one rule: before pushing a new element, pop all elements that violate the desired ordering. In a monotonically decreasing stack (largest at bottom, smallest at top), before pushing x, you pop every element smaller than x. The crucial observation: every pop event answers a query. When you pop element y because x is larger, you have just discovered that x is the "next greater element" for y. This is what makes monotonic stacks so powerful — they find relationships between elements as a side effect of the push/pop operations.

Template: next greater element (monotonic decreasing)

Key decisions: (1) store indices not values in the stack — you need to look up both the value (for comparison) and the position (to record the answer). (2) Initialize result with -1 (the "no greater element found" sentinel). (3) The while loop processes ALL elements that the current element is greater than — not just one. Daily Temperatures (LC 739) uses exactly this template with nums[i] representing the temperature.

Code template

def next_greater_elements(nums):
    n = len(nums)
    result = [-1] * n
    stack = []
    for i in range(n):
        while stack and nums[i] > nums[stack[-1]]:
            idx = stack.pop()
            result[idx] = nums[i]
        stack.append(i)
    return result

Template: largest rectangle (monotonic increasing)

The appended 0 flushes all remaining elements at the end. The width calculation uses the stack state to find the span — when the stack is empty, the bar extends all the way to the left boundary (width = i). This is the hardest monotonic stack template to derive from scratch; memorize it.

Code template

def largest_rectangle(heights):
    stack = []
    max_area = 0
    heights = heights + [0]
    for i, h in enumerate(heights):
        while stack and h < heights[stack[-1]]:
            height = heights[stack.pop()]
            width = i if not stack else i - stack[-1] - 1
            max_area = max(max_area, height * width)
        stack.append(i)
    return max_area

LC 42: Trapping Rain Water with monotonic stack

Trapping Rain Water (LC 42) is most commonly solved with two pointers (O(1) space), but the monotonic stack approach generalizes better to 2D versions. For each bar popped from the stack (call it the "bottom"), the water trapped between it and the current bar is: min(heights[left_boundary], heights[current]) - heights[bottom]) * (current - left_boundary - 1). The stack approach processes water layer by layer from the bottom up, making it more intuitive than the two-pointer left_max/right_max approach. In interviews, mention both approaches and explain the tradeoff: two-pointer is O(1) space; stack is easier to extend to 2D.

Circular array variant: Next Greater Element II (LC 503)

When the array is circular (you can look past the end back to the beginning), run the same algorithm twice over the concatenated array — or use index modulo. Only record results for i < n (first pass). The modulo trick handles circularity without actual array duplication. This pattern applies to any "next X in a circular array" problem.

Code template

def next_greater_elements(nums):
    n = len(nums)
    result = [-1] * n
    stack = []
    for i in range(2 * n):
        idx = i % n
        while stack and nums[idx] > nums[stack[-1]]:
            result[stack.pop()] = nums[idx]
        if i < n:          # only push indices in the first pass
            stack.append(idx)
    return result

Recognizing monotonic stack in disguise

Not all monotonic stack problems announce themselves. Car Fleet (LC 853) seems like a simulation problem but the key insight is that cars arriving in order form a natural stack — faster cars catch up to slower ones and merge into fleets. Asteroid Collision (LC 735) is explicitly a stack problem but requires handling multiple collision cases that a monotonic stack naturally resolves. Online Stock Span (LC 901) is a "previous greater element" problem in streaming form. The unifying signal: you need to find the nearest element satisfying a condition — this is always monotonic stack territory.

Frequently Asked Questions

What is a monotonic stack?
A monotonic stack is a stack where elements are maintained in strictly increasing or strictly decreasing order from bottom to top. When a new element is pushed, any elements that would violate the monotonic property are popped first. This popping event is the key insight: it is precisely when an element is popped that you learn the relationship between it and the element that caused the pop (e.g., the next greater element). Monotonic stacks convert O(n²) brute-force "for each element, scan right" problems into O(n) solutions.
When should I use a monotonic stack?
Reach for a monotonic stack when you need to find, for each element: the next greater element, the previous smaller element, the nearest larger element to either side, or the largest rectangle/area in a range. The signal phrases in problem statements are: "next greater", "next smaller", "daily temperatures", "largest rectangle", "trapping rain water", "stock span". If you see any of these, think monotonic stack before anything else.
What is the difference between a monotonic increasing and monotonic decreasing stack?
A monotonically increasing stack (bottom to top) is used when you want to find the next greater element — you pop when the new element is greater than the top. A monotonically decreasing stack is used when you want to find the next smaller element — you pop when the new element is smaller than the top. The choice is determined by what relationship you are trying to find: greater → decreasing stack (pop when you find something bigger); smaller → increasing stack (pop when you find something smaller). Confusing the two is the most common monotonic stack bug.
What are the most common monotonic stack LeetCode problems?
Must-know problems: Daily Temperatures (LC 739) — the canonical "next greater element" introduction. Largest Rectangle in Histogram (LC 84) — the hardest; uses a monotonically increasing stack to find the next smaller bar on both sides. Trapping Rain Water (LC 42) — can be solved with two-pointer or monotonic stack; the stack approach is more generalizable. Next Greater Element I and II (LC 496, 503) — the core pattern with a circular array variant. Car Fleet (LC 853) — monotonic stack applied to a non-obvious problem. Stock Span Problem (LC 901 / Design) — previous greater element.

Practice this pattern

See all problems and the code template →

Study pattern

Syed Peera Saheb

Software Engineer · 5+ years · ServiceNow

Software engineer with hands-on experience passing technical interviews at top tech companies. Built Coding Prep Guide to share the pattern-first prep strategy that actually works. Writes about DSA, system design, and interview strategy.

Buy me a coffee