Monotonic Stack Pattern: Template + 225 LeetCode Problems

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

  • 21 Easy
  • 115 Medium
  • 89 Hard
  • O(n) time

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.

Monotonic Stack — Python 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.

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)

#ProblemDifficultyTopics
35Search Insert PositionEasyArray, Binary Search
69Sqrt(x)EasyMath, Binary Search
222Count Complete Tree NodesEasyBit Manipulation, Tree, Binary Search +1
278First Bad VersionEasyBinary Search, Interactive
367Valid Perfect SquareEasyMath, Binary Search
374Guess Number Higher or LowerEasyBinary Search, Interactive
441Arranging CoinsEasyMath, Binary Search
496Next Greater Element IEasyStack, Array, Hash Table +1
704Binary SearchEasyArray, Binary Search
744Find Smallest Letter Greater Than TargetEasyArray, Binary Search
270Closest Binary Search Tree ValuePremiumEasyTree, Depth-First Search, Binary Search Tree +2
1064Fixed PointPremiumEasyArray, Binary Search
1150Check If a Number Is Majority Element in a Sorted ArrayPremiumEasyArray, Binary Search
1337The K Weakest Rows in a MatrixEasyArray, Binary Search, Matrix +2
1351Count Negative Numbers in a Sorted MatrixEasyArray, Binary Search, Matrix
1475Final Prices With a Special Discount in a ShopEasyStack, Array, Monotonic Stack
1539Kth Missing Positive NumberEasyArray, Binary Search
1608Special Array With X Elements Greater Than or Equal XEasyArray, Binary Search, Sorting
2089Find Target Indices After Sorting ArrayEasyArray, Binary Search, Sorting
2389Longest Subsequence With Limited SumEasyGreedy, Array, Binary Search +2
2529Maximum Count of Positive Integer and Negative IntegerEasyArray, Binary Search, Counting

Medium (115)

#ProblemDifficultyTopics
33Search in Rotated Sorted ArrayMediumArray, Binary Search
34Find First and Last Position of Element in Sorted ArrayMediumArray, Binary Search
74Search a 2D MatrixMediumArray, Binary Search, Matrix
81Search in Rotated Sorted Array IIMediumArray, Binary Search
153Find Minimum in Rotated Sorted ArrayMediumArray, Binary Search
162Find Peak ElementMediumArray, Binary Search
240Search a 2D Matrix IIMediumArray, Binary Search, Divide and Conquer +1
275H-Index IIMediumArray, Binary Search
300Longest Increasing SubsequenceMediumArray, Binary Search, Dynamic Programming
316Remove Duplicate LettersMediumStack, Greedy, String +1
378Kth Smallest Element in a Sorted MatrixMediumArray, Binary Search, Matrix +2
400Nth DigitMediumMath, Binary Search
402Remove K DigitsMediumStack, Greedy, String +1
436Find Right IntervalMediumArray, Binary Search, Sorting
456132 PatternMediumStack, Array, Binary Search +2
497Random Point in Non-overlapping RectanglesMediumReservoir Sampling, Array, Math +4
503Next Greater Element IIMediumStack, Array, Monotonic Stack
528Random Pick with WeightMediumArray, Math, Binary Search +2
540Single Element in a Sorted ArrayMediumArray, Binary Search
581Shortest Unsorted Continuous SubarrayMediumStack, Greedy, Array +3
654Maximum Binary TreeMediumStack, Tree, Array +3
729My Calendar IMediumDesign, Segment Tree, Array +2
731My Calendar IIMediumDesign, Segment Tree, Array +3
739Daily TemperaturesMediumStack, Array, Monotonic Stack
853Car FleetMediumStack, Array, Sorting +1
875Koko Eating BananasMediumArray, Binary Search
901Online Stock SpanMediumStack, Design, Data Stream +1
918Maximum Sum Circular SubarrayMediumQueue, Array, Divide and Conquer +2
1268Search Suggestions SystemMediumTrie, Array, String +3
255Verify Preorder Sequence in Binary Search TreePremiumMediumStack, Tree, Binary Search Tree +4
362Design Hit CounterPremiumMediumDesign, Queue, Array +2
702Search in a Sorted Array of Unknown SizePremiumMediumArray, Binary Search, Interactive
754Reach a NumberMediumMath, Binary Search
769Max Chunks To Make SortedMediumStack, Greedy, Array +2
852Peak Index in a Mountain ArrayMediumArray, Binary Search
907Sum of Subarray MinimumsMediumStack, Array, Dynamic Programming +1
962Maximum Width RampMediumStack, Array, Two Pointers +1
1008Construct Binary Search Tree from Preorder TraversalMediumStack, Tree, Binary Search Tree +3
1011Capacity To Ship Packages Within D DaysMediumArray, Binary Search
1019Next Greater Node In Linked ListMediumStack, Array, Linked List +1
1060Missing Element in Sorted ArrayPremiumMediumArray, Binary Search
1062Longest Repeating SubstringPremiumMediumString, Binary Search, Dynamic Programming +3
1081Smallest Subsequence of Distinct CharactersMediumStack, Greedy, String +1
1102Path With Maximum Minimum ValuePremiumMediumDepth-First Search, Breadth-First Search, Union Find +4
1124Longest Well-Performing IntervalMediumStack, Array, Hash Table +2
1130Minimum Cost Tree From Leaf ValuesMediumStack, Greedy, Array +2
1182Shortest Distance to Target ColorPremiumMediumArray, Binary Search, Dynamic Programming
1201Ugly Number IIIMediumMath, Binary Search, Combinatorics +1
1283Find the Smallest Divisor Given a ThresholdMediumArray, Binary Search
1292Maximum Side Length of a Square with Sum Less than or Equal to ThresholdMediumArray, Binary Search, Matrix +1
1300Sum of Mutated Array Closest to TargetMediumArray, Binary Search, Sorting
1428Leftmost Column with at Least a OnePremiumMediumArray, Binary Search, Interactive +1
1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitMediumQueue, Array, Ordered Set +3
1482Minimum Number of Days to Make m BouquetsMediumArray, Binary Search
1504Count Submatrices With All OnesMediumStack, Array, Dynamic Programming +2
1533Find the Index of the Large IntegerPremiumMediumArray, Binary Search, Interactive
1552Magnetic Force Between Two BallsMediumArray, Binary Search, Sorting
1574Shortest Subarray to be Removed to Make Array SortedMediumStack, Array, Two Pointers +2
1618Maximum Font to Fit a Sentence in a ScreenPremiumMediumArray, String, Binary Search +1
1631Path With Minimum EffortMediumDepth-First Search, Breadth-First Search, Union Find +4
1648Sell Diminishing-Valued Colored BallsMediumGreedy, Array, Math +3
1673Find the Most Competitive SubsequenceMediumStack, Greedy, Array +1
1696Jump Game VIMediumQueue, Array, Dynamic Programming +2
1760Minimum Limit of Balls in a BagMediumArray, Binary Search
1762Buildings With an Ocean ViewPremiumMediumStack, Array, Monotonic Stack
1802Maximum Value at a Given Index in a Bounded ArrayMediumGreedy, Math, Binary Search
1818Minimum Absolute Sum DifferenceMediumArray, Binary Search, Ordered Set +1
1856Maximum Subarray Min-ProductMediumStack, Array, Prefix Sum +1
1870Minimum Speed to Arrive on TimeMediumArray, Binary Search
1891Cutting RibbonsPremiumMediumArray, Binary Search
1894Find the Student that Will Replace the ChalkMediumArray, Binary Search, Prefix Sum +1
1901Find a Peak Element IIMediumArray, Binary Search, Matrix
1950Maximum of Minimum Values in All SubarraysPremiumMediumStack, Array, Monotonic Stack
1954Minimum Garden Perimeter to Collect Enough ApplesMediumMath, Binary Search
1966Binary Searchable Numbers in an Unsorted ArrayPremiumMediumArray, Binary Search
1996The Number of Weak Characters in the GameMediumStack, Greedy, Array +2
2054Two Best Non-Overlapping EventsMediumArray, Binary Search, Dynamic Programming +2
2055Plates Between CandlesMediumArray, String, Binary Search +1
2064Minimized Maximum of Products Distributed to Any StoreMediumGreedy, Array, Binary Search
2070Most Beautiful Item for Each QueryMediumArray, Binary Search, Sorting
2104Sum of Subarray RangesMediumStack, Array, Monotonic Stack
2137Pour Water Between Buckets to Make Water Levels EqualPremiumMediumArray, Binary Search
2187Minimum Time to Complete TripsMediumArray, Binary Search
2226Maximum Candies Allocated to K ChildrenMediumArray, Binary Search
2282Number of People That Can Be Seen in a GridPremiumMediumStack, Array, Matrix +1
2289Steps to Make Array Non-decreasingMediumStack, Array, Linked List +1
2297Jump Game VIIIPremiumMediumStack, Graph, Array +3
2333Minimum Sum of Squared DifferenceMediumGreedy, Array, Binary Search +2
2345Finding the Number of Visible MountainsPremiumMediumStack, Array, Sorting +1
2358Maximum Number of Groups Entering a CompetitionMediumGreedy, Array, Math +1
2387Median of a Row Wise Sorted MatrixPremiumMediumArray, Binary Search, Matrix
2439Minimize Maximum of ArrayMediumGreedy, Array, Binary Search +2
2476Closest Nodes Queries in a Binary Search TreeMediumTree, Depth-First Search, Binary Search Tree +3
2487Remove Nodes From Linked ListMediumStack, Recursion, Linked List +1
2498Frog Jump IIMediumGreedy, Array, Binary Search
2513Minimize the Maximum of Two ArraysMediumMath, Binary Search, Number Theory
2517Maximum Tastiness of Candy BasketMediumGreedy, Array, Binary Search +1
2557Maximum Number of Integers to Choose From a Range IIPremiumMediumGreedy, Array, Binary Search +1
2560House Robber IVMediumGreedy, Array, Binary Search +1
2594Minimum Time to Repair CarsMediumArray, Binary Search
2601Prime Subtraction OperationMediumGreedy, Array, Math +2
2602Minimum Operations to Make All Array Elements EqualMediumArray, Binary Search, Prefix Sum +1
2616Minimize the Maximum Difference of PairsMediumGreedy, Array, Binary Search +2
2762Continuous SubarraysMediumQueue, Array, Ordered Set +3
2812Find the Safest Path in a GridMediumBreadth-First Search, Union Find, Array +3
2817Minimum Absolute Difference Between Elements With ConstraintMediumArray, Binary Search, Ordered Set
2826Sorting Three GroupsMediumArray, Binary Search, Dynamic Programming
2832Maximal Range That Each Element Is Maximum in ItPremiumMediumStack, Array, Monotonic Stack
2861Maximum Number of AlloysMediumArray, Binary Search
2863Maximum Length of Semi-Decreasing SubarraysPremiumMediumStack, Array, Sorting +1
2865Beautiful Towers IMediumStack, Array, Monotonic Stack
2866Beautiful Towers IIMediumStack, Array, Monotonic Stack
2936Number of Equal Numbers BlocksPremiumMediumArray, Binary Search, Interactive
2944Minimum Number of Coins for FruitsMediumQueue, Array, Dynamic Programming +2
2967Minimum Cost to Make Array EqualindromicMediumGreedy, Array, Math +2

Hard (89)

#ProblemDifficultyTopics
4Median of Two Sorted ArraysHardArray, Binary Search, Divide and Conquer
42Trapping Rain WaterHardStack, Array, Two Pointers +2
84Largest Rectangle in HistogramHardStack, Array, Monotonic Stack
85Maximal RectangleHardStack, Array, Dynamic Programming +2
154Find Minimum in Rotated Sorted Array IIHardArray, Binary Search
239Sliding Window MaximumHardQueue, Array, Sliding Window +2
315Count of Smaller Numbers After SelfHardBinary Indexed Tree, Segment Tree, Array +4
321Create Maximum NumberHardStack, Greedy, Array +2
327Count of Range SumHardBinary Indexed Tree, Segment Tree, Array +4
354Russian Doll EnvelopesHardArray, Binary Search, Dynamic Programming +1
363Max Sum of Rectangle No Larger Than KHardArray, Binary Search, Matrix +2
410Split Array Largest SumHardGreedy, Array, Binary Search +2
483Smallest Good BaseHardMath, Binary Search
493Reverse PairsHardBinary Indexed Tree, Segment Tree, Array +4
668Kth Smallest Number in Multiplication TableHardMath, Binary Search
732My Calendar IIIHardDesign, Segment Tree, Binary Search +2
778Swim in Rising WaterHardDepth-First Search, Breadth-First Search, Union Find +4
1235Maximum Profit in Job SchedulingHardArray, Binary Search, Dynamic Programming +1
1851Minimum Interval to Include Each QueryHardArray, Binary Search, Sorting +2
302Smallest Rectangle Enclosing Black PixelsPremiumHardDepth-First Search, Breadth-First Search, Array +2
644Maximum Average Subarray IIPremiumHardArray, Binary Search, Prefix Sum
683K Empty SlotsPremiumHardBinary Indexed Tree, Segment Tree, Queue +5
768Max Chunks To Make Sorted IIHardStack, Greedy, Array +2
774Minimize Max Distance to Gas StationPremiumHardArray, Binary Search
793Preimage Size of Factorial Zeroes FunctionHardMath, Binary Search
862Shortest Subarray with Sum at Least KHardQueue, Array, Binary Search +4
878Nth Magical NumberHardMath, Binary Search
887Super Egg DropHardMath, Binary Search, Dynamic Programming
902Numbers At Most N Given Digit SetHardArray, Math, String +2
975Odd Even JumpHardStack, Array, Dynamic Programming +3
1063Number of Valid SubarraysPremiumHardStack, Array, Monotonic Stack
1095Find in Mountain ArrayHardArray, Binary Search, Interactive
1157Online Majority Element In SubarrayHardDesign, Binary Indexed Tree, Segment Tree +2
1187Make Array Strictly IncreasingHardArray, Binary Search, Dynamic Programming +1
1231Divide ChocolatePremiumHardArray, Binary Search
1425Constrained Subsequence SumHardQueue, Array, Dynamic Programming +3
1439Find the Kth Smallest Sum of a Matrix With Sorted RowsHardArray, Binary Search, Matrix +1
1483Kth Ancestor of a Tree NodeHardBit Manipulation, Tree, Depth-First Search +4
1499Max Value of EquationHardQueue, Array, Sliding Window +2
1521Find a Value of a Mysterious Function Closest to TargetHardBit Manipulation, Segment Tree, Array +1
1526Minimum Number of Increments on Subarrays to Form a Target ArrayHardStack, Greedy, Array +2
1649Create Sorted Array through InstructionsHardBinary Indexed Tree, Segment Tree, Array +4
1671Minimum Number of Removals to Make Mountain ArrayHardGreedy, Array, Binary Search +1
1687Delivering Boxes from Storage to PortsHardSegment Tree, Queue, Array +4
1739Building BoxesHardGreedy, Math, Binary Search
1751Maximum Number of Events That Can Be Attended IIHardArray, Binary Search, Dynamic Programming +1
1776Car Fleet IIHardStack, Array, Math +2
1793Maximum Score of a Good SubarrayHardStack, Array, Two Pointers +2
1847Closest RoomHardArray, Binary Search, Ordered Set +1
1862Sum of Floored PairsHardArray, Math, Binary Search +1
1889Minimum Space Wasted From PackagingHardArray, Binary Search, Prefix Sum +1
1923Longest Common SubpathHardArray, Binary Search, Suffix Array +2
1944Number of Visible People in a QueueHardStack, Array, Monotonic Stack
1956Minimum Time For K Virus Variants to SpreadPremiumHardGeometry, Array, Math +2
1964Find the Longest Valid Obstacle Course at Each PositionHardBinary Indexed Tree, Array, Binary Search
1970Last Day Where You Can Still CrossHardDepth-First Search, Breadth-First Search, Union Find +3
2030Smallest K-Length Subsequence With Occurrences of a LetterHardStack, Greedy, String +1
2040Kth Smallest Product of Two Sorted ArraysHardArray, Binary Search
2071Maximum Number of Tasks You Can AssignHardGreedy, Queue, Array +4
2111Minimum Operations to Make the Array K-IncreasingHardArray, Binary Search
2141Maximum Running Time of N ComputersHardGreedy, Array, Binary Search +1
2179Count Good Triplets in an ArrayHardBinary Indexed Tree, Segment Tree, Array +4
2223Sum of Scores of Built StringsHardString, Binary Search, String Matching +3
2258Escape the Spreading FireHardBreadth-First Search, Array, Binary Search +1
2281Sum of Total Strength of WizardsHardStack, Array, Prefix Sum +1
2286Booking Concert Tickets in GroupsHardDesign, Binary Indexed Tree, Segment Tree +1
2334Subarray With Elements Greater Than Varying ThresholdHardStack, Union Find, Array +1
2355Maximum Number of Books You Can TakePremiumHardStack, Array, Dynamic Programming +1
2398Maximum Number of Robots Within BudgetHardQueue, Array, Binary Search +4
2407Longest Increasing Subsequence IIHardBinary Indexed Tree, Segment Tree, Queue +4
2426Number of Pairs Satisfying InequalityHardBinary Indexed Tree, Segment Tree, Array +4
2444Count Subarrays With Fixed BoundsHardQueue, Array, Sliding Window +1
2448Minimum Cost to Make Array EqualHardGreedy, Array, Binary Search +2
2454Next Greater Element IVHardStack, Array, Binary Search +3
2468Split Message Based on LimitHardString, Binary Search, Enumeration
2519Count the Number of K-Big IndicesPremiumHardBinary Indexed Tree, Segment Tree, Array +4
2589Minimum Time to Complete All TasksHardStack, Greedy, Array +2
2617Minimum Number of Visited Cells in a GridHardStack, Breadth-First Search, Union Find +5
2659Make Array EmptyHardGreedy, Binary Indexed Tree, Segment Tree +4
2702Minimum Operations to Make Numbers Non-positivePremiumHardArray, Binary Search
2736Maximum Sum QueriesHardStack, Binary Indexed Tree, Segment Tree +4
2790Maximum Number of Groups With Increasing LengthHardGreedy, Array, Math +2
2818Apply Operations to Maximize ScoreHardStack, Greedy, Array +4
2819Minimum Relative Loss After Buying ChocolatesPremiumHardArray, Binary Search, Prefix Sum +1
2926Maximum Balanced Subsequence SumHardBinary Indexed Tree, Segment Tree, Array +2
2940Find Building Where Alice and Bob Can MeetHardStack, Binary Indexed Tree, Segment Tree +4
2941Maximum GCD-Sum of a SubarrayPremiumHardArray, Math, Binary Search +1
2945Find Maximum Non-decreasing Array LengthHardStack, Queue, Array +4
2969Minimum Number of Coins for Fruits IIPremiumHardQueue, Array, Dynamic Programming +2

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

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.

Meet the monotonic stack problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.