Pattern 06 of 22

Monotonic Stack Pattern: Template + 225 LeetCode Problems

Answer "what is the next greater element" for every position in one pass.

Easy
21
Medium
115
Hard
89
Time
O(n)

What the monotonic stack pattern is

A monotonic stack is an ordinary stack with one invariant added: its contents are kept increasing or decreasing, and any element that would break the order is popped first. The pops are the algorithm. When a new value evicts the elements below it, that new value is by construction the nearest element to their right that is larger — so "next greater element" for every index falls out of a single left-to-right scan rather than an O(n²) search. The total cost stays linear because each index is pushed once and popped once, no matter how expensive an individual step looks. Pick the direction from the question: a decreasing stack surrenders its top to a larger arrival and answers next-greater queries, an increasing stack answers next-smaller, and storing indices rather than values is almost always right because the distance between them is usually part of the answer.

When to use it

  • The question is about the nearest larger or smaller element in some direction.
  • You are computing spans, widths or distances between a position and the first position that beats it.
  • A histogram, a skyline, temperatures, or stock spans are involved.
  • The brute force scans right from every index until it finds something bigger.

The monotonic stack template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 225 problems listed below.

PythonMonotonic Stack template
def next_greater(nums):
    result = [-1] * len(nums)
    stack = []                       # indices; their values stay decreasing

    for i, value in enumerate(nums):
        # every index this value evicts has just found its next greater element
        while stack and nums[stack[-1]] < value:
            result[stack.pop()] = value
        stack.append(i)

    return result

Complexity characteristics

Time
O(n)
Auxiliary space
O(n)

Each index is pushed exactly once and popped at most once, so the inner while loop does not multiply the outer loop: the total number of pops over the whole scan is bounded by n even though one step can pop many elements. The stack is the space, and it holds all n indices in the worst case — an input already sorted in the direction the stack maintains never pops anything until the end.

Eyes only

Meet the monotonic stack problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 225 monotonic stack LeetCode problems

Every problem in the library the monotonic stack pattern applies to, grouped by LeetCode's own difficulty rating. 184 of the 225 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (21)

Easy problems
No.Problem
0035Search Insert Position
0069Sqrt(x)
0222Count Complete Tree Nodes
0278First Bad Version
0367Valid Perfect Square
0374Guess Number Higher or Lower
0441Arranging Coins
0496Next Greater Element I
0704Binary Search
0744Find Smallest Letter Greater Than Target
0270Closest Binary Search Tree ValuePremium
1064Fixed PointPremium
1150Check If a Number Is Majority Element in a Sorted ArrayPremium
1337The K Weakest Rows in a Matrix
1351Count Negative Numbers in a Sorted Matrix
1475Final Prices With a Special Discount in a Shop
1539Kth Missing Positive Number
1608Special Array With X Elements Greater Than or Equal X
2089Find Target Indices After Sorting Array
2389Longest Subsequence With Limited Sum
2529Maximum Count of Positive Integer and Negative Integer

Medium (115)

Medium problems
No.Problem
0033Search in Rotated Sorted Array
0034Find First and Last Position of Element in Sorted Array
0074Search a 2D Matrix
0081Search in Rotated Sorted Array II
0153Find Minimum in Rotated Sorted Array
0162Find Peak Element
0240Search a 2D Matrix II
0275H-Index II
0300Longest Increasing Subsequence
0316Remove Duplicate Letters
0378Kth Smallest Element in a Sorted Matrix
0400Nth Digit
0402Remove K Digits
0436Find Right Interval
0456132 Pattern
0497Random Point in Non-overlapping Rectangles
0503Next Greater Element II
0528Random Pick with Weight
0540Single Element in a Sorted Array
0581Shortest Unsorted Continuous Subarray
0654Maximum Binary Tree
0729My Calendar I
0731My Calendar II
0739Daily Temperatures
0853Car Fleet
0875Koko Eating Bananas
0901Online Stock Span
0918Maximum Sum Circular Subarray
1268Search Suggestions System
0255Verify Preorder Sequence in Binary Search TreePremium
0362Design Hit CounterPremium
0702Search in a Sorted Array of Unknown SizePremium
0754Reach a Number
0769Max Chunks To Make Sorted
0852Peak Index in a Mountain Array
0907Sum of Subarray Minimums
0962Maximum Width Ramp
1008Construct Binary Search Tree from Preorder Traversal
1011Capacity To Ship Packages Within D Days
1019Next Greater Node In Linked List
1060Missing Element in Sorted ArrayPremium
1062Longest Repeating SubstringPremium
1081Smallest Subsequence of Distinct Characters
1102Path With Maximum Minimum ValuePremium
1124Longest Well-Performing Interval
1130Minimum Cost Tree From Leaf Values
1182Shortest Distance to Target ColorPremium
1201Ugly Number III
1283Find the Smallest Divisor Given a Threshold
1292Maximum Side Length of a Square with Sum Less than or Equal to Threshold
1300Sum of Mutated Array Closest to Target
1428Leftmost Column with at Least a OnePremium
1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
1482Minimum Number of Days to Make m Bouquets
1504Count Submatrices With All Ones
1533Find the Index of the Large IntegerPremium
1552Magnetic Force Between Two Balls
1574Shortest Subarray to be Removed to Make Array Sorted
1618Maximum Font to Fit a Sentence in a ScreenPremium
1631Path With Minimum Effort
1648Sell Diminishing-Valued Colored Balls
1673Find the Most Competitive Subsequence
1696Jump Game VI
1760Minimum Limit of Balls in a Bag
1762Buildings With an Ocean ViewPremium
1802Maximum Value at a Given Index in a Bounded Array
1818Minimum Absolute Sum Difference
1856Maximum Subarray Min-Product
1870Minimum Speed to Arrive on Time
1891Cutting RibbonsPremium
1894Find the Student that Will Replace the Chalk
1901Find a Peak Element II
1950Maximum of Minimum Values in All SubarraysPremium
1954Minimum Garden Perimeter to Collect Enough Apples
1966Binary Searchable Numbers in an Unsorted ArrayPremium
1996The Number of Weak Characters in the Game
2054Two Best Non-Overlapping Events
2055Plates Between Candles
2064Minimized Maximum of Products Distributed to Any Store
2070Most Beautiful Item for Each Query
2104Sum of Subarray Ranges
2137Pour Water Between Buckets to Make Water Levels EqualPremium
2187Minimum Time to Complete Trips
2226Maximum Candies Allocated to K Children
2282Number of People That Can Be Seen in a GridPremium
2289Steps to Make Array Non-decreasing
2297Jump Game VIIIPremium
2333Minimum Sum of Squared Difference
2345Finding the Number of Visible MountainsPremium
2358Maximum Number of Groups Entering a Competition
2387Median of a Row Wise Sorted MatrixPremium
2439Minimize Maximum of Array
2476Closest Nodes Queries in a Binary Search Tree
2487Remove Nodes From Linked List
2498Frog Jump II
2513Minimize the Maximum of Two Arrays
2517Maximum Tastiness of Candy Basket
2557Maximum Number of Integers to Choose From a Range IIPremium
2560House Robber IV
2594Minimum Time to Repair Cars
2601Prime Subtraction Operation
2602Minimum Operations to Make All Array Elements Equal
2616Minimize the Maximum Difference of Pairs
2762Continuous Subarrays
2812Find the Safest Path in a Grid
2817Minimum Absolute Difference Between Elements With Constraint
2826Sorting Three Groups
2832Maximal Range That Each Element Is Maximum in ItPremium
2861Maximum Number of Alloys
2863Maximum Length of Semi-Decreasing SubarraysPremium
2865Beautiful Towers I
2866Beautiful Towers II
2936Number of Equal Numbers BlocksPremium
2944Minimum Number of Coins for Fruits
2967Minimum Cost to Make Array Equalindromic

Hard (89)

Hard problems
No.Problem
0004Median of Two Sorted Arrays
0042Trapping Rain Water
0084Largest Rectangle in Histogram
0085Maximal Rectangle
0154Find Minimum in Rotated Sorted Array II
0239Sliding Window Maximum
0315Count of Smaller Numbers After Self
0321Create Maximum Number
0327Count of Range Sum
0354Russian Doll Envelopes
0363Max Sum of Rectangle No Larger Than K
0410Split Array Largest Sum
0483Smallest Good Base
0493Reverse Pairs
0668Kth Smallest Number in Multiplication Table
0732My Calendar III
0778Swim in Rising Water
1235Maximum Profit in Job Scheduling
1851Minimum Interval to Include Each Query
0302Smallest Rectangle Enclosing Black PixelsPremium
0644Maximum Average Subarray IIPremium
0683K Empty SlotsPremium
0768Max Chunks To Make Sorted II
0774Minimize Max Distance to Gas StationPremium
0793Preimage Size of Factorial Zeroes Function
0862Shortest Subarray with Sum at Least K
0878Nth Magical Number
0887Super Egg Drop
0902Numbers At Most N Given Digit Set
0975Odd Even Jump
1063Number of Valid SubarraysPremium
1095Find in Mountain Array
1157Online Majority Element In Subarray
1187Make Array Strictly Increasing
1231Divide ChocolatePremium
1425Constrained Subsequence Sum
1439Find the Kth Smallest Sum of a Matrix With Sorted Rows
1483Kth Ancestor of a Tree Node
1499Max Value of Equation
1521Find a Value of a Mysterious Function Closest to Target
1526Minimum Number of Increments on Subarrays to Form a Target Array
1649Create Sorted Array through Instructions
1671Minimum Number of Removals to Make Mountain Array
1687Delivering Boxes from Storage to Ports
1739Building Boxes
1751Maximum Number of Events That Can Be Attended II
1776Car Fleet II
1793Maximum Score of a Good Subarray
1847Closest Room
1862Sum of Floored Pairs
1889Minimum Space Wasted From Packaging
1923Longest Common Subpath
1944Number of Visible People in a Queue
1956Minimum Time For K Virus Variants to SpreadPremium
1964Find the Longest Valid Obstacle Course at Each Position
1970Last Day Where You Can Still Cross
2030Smallest K-Length Subsequence With Occurrences of a Letter
2040Kth Smallest Product of Two Sorted Arrays
2071Maximum Number of Tasks You Can Assign
2111Minimum Operations to Make the Array K-Increasing
2141Maximum Running Time of N Computers
2179Count Good Triplets in an Array
2223Sum of Scores of Built Strings
2258Escape the Spreading Fire
2281Sum of Total Strength of Wizards
2286Booking Concert Tickets in Groups
2334Subarray With Elements Greater Than Varying Threshold
2355Maximum Number of Books You Can TakePremium
2398Maximum Number of Robots Within Budget
2407Longest Increasing Subsequence II
2426Number of Pairs Satisfying Inequality
2444Count Subarrays With Fixed Bounds
2448Minimum Cost to Make Array Equal
2454Next Greater Element IV
2468Split Message Based on Limit
2519Count the Number of K-Big IndicesPremium
2589Minimum Time to Complete All Tasks
2617Minimum Number of Visited Cells in a Grid
2659Make Array Empty
2702Minimum Operations to Make Numbers Non-positivePremium
2736Maximum Sum Queries
2790Maximum Number of Groups With Increasing Length
2818Apply Operations to Maximize Score
2819Minimum Relative Loss After Buying ChocolatesPremium
2926Maximum Balanced Subsequence Sum
2940Find Building Where Alice and Bob Can Meet
2941Maximum GCD-Sum of a SubarrayPremium
2945Find Maximum Non-decreasing Array Length
2969Minimum Number of Coins for Fruits IIPremium

Monotonic Stack pattern FAQ

What is the monotonic stack pattern?

A monotonic stack is an ordinary stack with one invariant added: its contents are kept increasing or decreasing, and any element that would break the order is popped first.

How many LeetCode problems use the monotonic stack pattern?

This page lists 225 LeetCode problems that the monotonic stack pattern applies to: 21 Easy, 115 Medium and 89 Hard. 184 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the monotonic stack pattern?

O(n) time and O(n) space. Each index is pushed exactly once and popped at most once, so the inner while loop does not multiply the outer loop: the total number of pops over the whole scan is bounded by n even though one step can pop many elements. The stack is the space, and it holds all n indices in the worst case — an input already sorted in the direction the stack maintains never pops anything until the end.

When should I use the monotonic stack pattern in an interview?

The question is about the nearest larger or smaller element in some direction. You are computing spans, widths or distances between a position and the first position that beats it.

Which monotonic stack problem should I start with?

LeetCode 35. Search Insert Position is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to monotonic stack?

Stack, Sliding Window, Two Pointers, Greedy. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.