Stack Pattern: Template + 194 LeetCode Problems

When the most recent unresolved thing is the one that matters, use a stack.

  • 26 Easy
  • 107 Medium
  • 61 Hard
  • O(n) time

What the stack pattern is

A stack is the right structure whenever the most recent unresolved item is the one a new element interacts with — which is another way of saying the input is nested. Brackets, directory paths, HTML tags, arithmetic expressions and undo histories are all the same problem: push when something opens, pop when the thing that closes it arrives, and the input is well-formed exactly when the pop matches and the stack ends empty. Both failure modes matter and both are commonly missed — a closing token arriving at an empty stack is as wrong as leftover items at the end. The second use is deferring work rather than matching it: an explicit stack is how a recursive traversal is rewritten iteratively when recursion is forbidden or the depth would overflow, and the only subtlety is that children must be pushed in reverse order to be visited in the intended one. When the stack additionally has to stay sorted, it becomes a monotonic stack, which is a different pattern with a different purpose.

When to use it

  • The input nests: brackets, tags, paths, expressions, nested encodings.
  • A new element resolves against the most recent unmatched one rather than the oldest.
  • A recursive solution exists but recursion is banned or would exceed the depth limit.
  • Work has to be undone, or evaluated in the reverse of the order it arrived.

The 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 194 problems listed below.

Stack — Python template
def is_balanced(s):
    closing = {")": "(", "]": "[", "}": "{"}
    stack = []

    for char in s:
        if char in closing:
            if not stack or stack.pop() != closing[char]:
                return False       # closed something that was never opened
        else:
            stack.append(char)

    return not stack               # anything still open is unbalanced

Complexity characteristics

Time
O(n)
Auxiliary space
O(n)

A single pass that pushes and pops each token at most once. The stack grows to the maximum nesting depth, which is n for an input that opens everything before closing anything, so the worst-case space is linear even when the typical case is shallow. Rewriting a recursion with an explicit stack changes neither figure — it moves the same frames off the call stack, which is usually the entire point.

All 194 stack LeetCode problems

Every problem in the library the stack pattern applies to, grouped by LeetCode's own difficulty rating. 154 of the 194 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 (26)

#ProblemDifficultyTopics
20Valid ParenthesesEasyStack, String
94Binary Tree Inorder TraversalEasyStack, Tree, Depth-First Search +1
144Binary Tree Preorder TraversalEasyStack, Tree, Depth-First Search +1
145Binary Tree Postorder TraversalEasyStack, Tree, Depth-First Search +1
225Implement Stack using QueuesEasyStack, Design, Queue
232Implement Queue using StacksEasyStack, Design, Queue
234Palindrome Linked ListEasyStack, Recursion, Linked List +1
387First Unique Character in a StringEasyQueue, Hash Table, String +1
496Next Greater Element IEasyStack, Array, Hash Table +1
589N-ary Tree Preorder TraversalEasyStack, Tree, Depth-First Search
590N-ary Tree Postorder TraversalEasyStack, Tree, Depth-First Search
682Baseball GameEasyStack, Array, Simulation
933Number of Recent CallsEasyDesign, Queue, Data Stream
346Moving Average from Data StreamPremiumEasyDesign, Queue, Array +1
844Backspace String CompareEasyStack, Two Pointers, String +1
897Increasing Order Search TreeEasyStack, Tree, Depth-First Search +2
1021Remove Outermost ParenthesesEasyStack, String
1047Remove All Adjacent Duplicates In StringEasyStack, String
1475Final Prices With a Special Discount in a ShopEasyStack, Array, Monotonic Stack
1544Make The String GreatEasyStack, String
1598Crawler Log FolderEasyStack, Array, String
1614Maximum Nesting Depth of the ParenthesesEasyStack, String
1700Number of Students Unable to Eat LunchEasyStack, Queue, Array +1
2000Reverse Prefix of WordEasyStack, Two Pointers, String
2073Time Needed to Buy TicketsEasyQueue, Array, Simulation
2696Minimum String Length After Removing SubstringsEasyStack, String, Simulation

Medium (107)

#ProblemDifficultyTopics
71Simplify PathMediumStack, String
114Flatten Binary Tree to Linked ListMediumStack, Tree, Depth-First Search +2
143Reorder ListMediumStack, Recursion, Linked List +1
150Evaluate Reverse Polish NotationMediumStack, Array, Math
155Min StackMediumStack, Design
173Binary Search Tree IteratorMediumStack, Tree, Design +3
227Basic Calculator IIMediumStack, Math, String
316Remove Duplicate LettersMediumStack, Greedy, String +1
331Verify Preorder Serialization of a Binary TreeMediumStack, Tree, String +1
341Flatten Nested List IteratorMediumStack, Tree, Depth-First Search +3
385Mini ParserMediumStack, Depth-First Search, String
388Longest Absolute File PathMediumStack, Depth-First Search, String
394Decode StringMediumStack, Recursion, String
402Remove K DigitsMediumStack, Greedy, String +1
445Add Two Numbers IIMediumStack, Linked List, Math
456132 PatternMediumStack, Array, Binary Search +2
503Next Greater Element IIMediumStack, Array, Monotonic Stack
581Shortest Unsorted Continuous SubarrayMediumStack, Greedy, Array +3
622Design Circular QueueMediumDesign, Queue, Array +1
636Exclusive Time of FunctionsMediumStack, Array
641Design Circular DequeMediumDesign, Queue, Array +1
649Dota2 SenateMediumGreedy, Queue, String
654Maximum Binary TreeMediumStack, Tree, Array +3
678Valid Parenthesis StringMediumStack, Greedy, String +1
735Asteroid CollisionMediumStack, Array, Simulation
739Daily TemperaturesMediumStack, Array, Monotonic Stack
853Car FleetMediumStack, Array, Sorting +1
901Online Stock SpanMediumStack, Design, Data Stream +1
918Maximum Sum Circular SubarrayMediumQueue, Array, Divide and Conquer +2
2130Maximum Twin Sum of a Linked ListMediumStack, Linked List, Two Pointers
2390Removing Stars From a StringMediumStack, String, Simulation
255Verify Preorder Sequence in Binary Search TreePremiumMediumStack, Tree, Binary Search Tree +4
281Zigzag IteratorPremiumMediumDesign, Queue, Array +1
353Design Snake GamePremiumMediumDesign, Queue, Array +2
362Design Hit CounterPremiumMediumDesign, Queue, Array +2
364Nested List Weight Sum IIPremiumMediumStack, Depth-First Search, Breadth-First Search
379Design Phone DirectoryPremiumMediumDesign, Queue, Array +2
426Convert Binary Search Tree to Sorted Doubly Linked ListPremiumMediumStack, Tree, Depth-First Search +4
439Ternary Expression ParserPremiumMediumStack, Recursion, String
484Find PermutationPremiumMediumStack, Greedy, Array +1
536Construct Binary Tree from StringPremiumMediumStack, Tree, Depth-First Search +2
769Max Chunks To Make SortedMediumStack, Greedy, Array +2
856Score of ParenthesesMediumStack, String
880Decoded String at IndexMediumStack, String
907Sum of Subarray MinimumsMediumStack, Array, Dynamic Programming +1
921Minimum Add to Make Parentheses ValidMediumStack, Greedy, String
946Validate Stack SequencesMediumStack, Array, Simulation
950Reveal Cards In Increasing OrderMediumQueue, Array, Sorting +1
962Maximum Width RampMediumStack, Array, Two Pointers +1
1003Check If Word Is Valid After SubstitutionsMediumStack, String
1006Clumsy FactorialMediumStack, Math, Simulation
1008Construct Binary Search Tree from Preorder TraversalMediumStack, Tree, Binary Search Tree +3
1019Next Greater Node In Linked ListMediumStack, Array, Linked List +1
1081Smallest Subsequence of Distinct CharactersMediumStack, Greedy, String +1
1087Brace ExpansionPremiumMediumStack, Breadth-First Search, String +2
1111Maximum Nesting Depth of Two Valid Parentheses StringsMediumStack, String
1124Longest Well-Performing IntervalMediumStack, Array, Hash Table +2
1130Minimum Cost Tree From Leaf ValuesMediumStack, Greedy, Array +2
1190Reverse Substrings Between Each Pair of ParenthesesMediumStack, String
1209Remove All Adjacent Duplicates in String IIMediumStack, String
1214Two Sum BSTsPremiumMediumStack, Tree, Depth-First Search +4
1249Minimum Remove to Make Valid ParenthesesMediumStack, String
1265Print Immutable Linked List in ReversePremiumMediumStack, Recursion, Linked List +1
1381Design a Stack With Increment OperationMediumStack, Design, Array
1429First Unique NumberPremiumMediumDesign, Queue, Array +2
1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitMediumQueue, Array, Ordered Set +3
1441Build an Array With Stack OperationsMediumStack, Array, Simulation
1472Design Browser HistoryMediumStack, Design, Array +3
1504Count Submatrices With All OnesMediumStack, Array, Dynamic Programming +2
1541Minimum Insertions to Balance a Parentheses StringMediumStack, Greedy, String
1574Shortest Subarray to be Removed to Make Array SortedMediumStack, Array, Two Pointers +2
1586Binary Search Tree Iterator IIPremiumMediumStack, Tree, Design +3
1628Design an Expression Tree With Evaluate FunctionPremiumMediumStack, Tree, Design +3
1653Minimum Deletions to Make String BalancedMediumStack, String, Dynamic Programming
1670Design Front Middle Back QueueMediumDesign, Queue, Array +2
1673Find the Most Competitive SubsequenceMediumStack, Greedy, Array +1
1696Jump Game VIMediumQueue, Array, Dynamic Programming +2
1717Maximum Score From Removing SubstringsMediumStack, Greedy, String
1762Buildings With an Ocean ViewPremiumMediumStack, Array, Monotonic Stack
1823Find the Winner of the Circular GameMediumRecursion, Queue, Array +2
1856Maximum Subarray Min-ProductMediumStack, Array, Prefix Sum +1
1910Remove All Occurrences of a SubstringMediumStack, String, Simulation
1950Maximum of Minimum Values in All SubarraysPremiumMediumStack, Array, Monotonic Stack
1963Minimum Number of Swaps to Make the String BalancedMediumStack, Greedy, Two Pointers +1
1996The Number of Weak Characters in the GameMediumStack, Greedy, Array +2
2104Sum of Subarray RangesMediumStack, Array, Monotonic Stack
2116Check if a Parentheses String Can Be ValidMediumStack, Greedy, String
2211Count Collisions on a RoadMediumStack, String, Simulation
2216Minimum Deletions to Make Array BeautifulMediumStack, Greedy, Array
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
2327Number of People Aware of a SecretMediumQueue, Dynamic Programming, Simulation
2345Finding the Number of Visible MountainsPremiumMediumStack, Array, Sorting +1
2375Construct Smallest Number From DI StringMediumStack, Greedy, String +1
2434Using a Robot to Print the Lexicographically Smallest StringMediumStack, Greedy, Hash Table +1
2487Remove Nodes From Linked ListMediumStack, Recursion, Linked List +1
2526Find Consecutive Integers from a Data StreamMediumDesign, Queue, Hash Table +2
2645Minimum Additions to Make Valid StringMediumStack, Greedy, String +1
2762Continuous SubarraysMediumQueue, Array, Ordered Set +3
2764Is Array a Preorder of Some ‌Binary TreePremiumMediumStack, Tree, Depth-First Search +1
2816Double a Number Represented as a Linked ListMediumStack, Linked List, Math
2832Maximal Range That Each Element Is Maximum in ItPremiumMediumStack, Array, Monotonic Stack
2863Maximum Length of Semi-Decreasing SubarraysPremiumMediumStack, Array, Sorting +1
2865Beautiful Towers IMediumStack, Array, Monotonic Stack
2866Beautiful Towers IIMediumStack, Array, Monotonic Stack
2944Minimum Number of Coins for FruitsMediumQueue, Array, Dynamic Programming +2

Hard (61)

#ProblemDifficultyTopics
32Longest Valid ParenthesesHardStack, String, Dynamic Programming
42Trapping Rain WaterHardStack, Array, Two Pointers +2
84Largest Rectangle in HistogramHardStack, Array, Monotonic Stack
85Maximal RectangleHardStack, Array, Dynamic Programming +2
224Basic CalculatorHardStack, Recursion, Math +1
239Sliding Window MaximumHardQueue, Array, Sliding Window +2
321Create Maximum NumberHardStack, Greedy, Array +2
488Zuma GameHardStack, Breadth-First Search, Memoization +2
591Tag ValidatorHardStack, String
736Parse Lisp ExpressionHardStack, Recursion, Hash Table +1
272Closest Binary Search Tree Value IIPremiumHardStack, Tree, Depth-First Search +4
683K Empty SlotsPremiumHardBinary Indexed Tree, Segment Tree, Queue +5
716Max StackPremiumHardStack, Design, Linked List +2
726Number of AtomsHardStack, Hash Table, String +1
768Max Chunks To Make Sorted IIHardStack, Greedy, Array +2
770Basic Calculator IVHardStack, Recursion, Hash Table +2
772Basic Calculator IIIPremiumHardStack, Recursion, Math +1
862Shortest Subarray with Sum at Least KHardQueue, Array, Binary Search +4
895Maximum Frequency StackHardStack, Design, Hash Table +1
936Stamping The SequenceHardStack, Greedy, Queue +1
975Odd Even JumpHardStack, Array, Dynamic Programming +3
995Minimum Number of K Consecutive Bit FlipsHardBit Manipulation, Queue, Array +2
1063Number of Valid SubarraysPremiumHardStack, Array, Monotonic Stack
1096Brace Expansion IIHardStack, Breadth-First Search, Hash Table +3
1106Parsing A Boolean ExpressionHardStack, Recursion, String
1172Dinner Plate StacksHardStack, Design, Hash Table +1
1425Constrained Subsequence SumHardQueue, Array, Dynamic Programming +3
1499Max Value of EquationHardQueue, Array, Sliding Window +2
1526Minimum Number of Increments on Subarrays to Form a Target ArrayHardStack, Greedy, Array +2
1597Build Binary Expression Tree From Infix ExpressionPremiumHardStack, Tree, String +1
1687Delivering Boxes from Storage to PortsHardSegment Tree, Queue, Array +4
1776Car Fleet IIHardStack, Array, Math +2
1793Maximum Score of a Good SubarrayHardStack, Array, Two Pointers +2
1825Finding MK AverageHardDesign, Queue, Data Stream +2
1896Minimum Cost to Change the Final Value of ExpressionHardStack, Math, String +1
1944Number of Visible People in a QueueHardStack, Array, Monotonic Stack
2019The Score of Students Solving Math ExpressionHardStack, Memoization, Array +4
2030Smallest K-Length Subsequence With Occurrences of a LetterHardStack, Greedy, String +1
2071Maximum Number of Tasks You Can AssignHardGreedy, Queue, Array +4
2197Replace Non-Coprime Numbers in ArrayHardStack, Array, Math +1
2254Design Video Sharing PlatformPremiumHardStack, Design, Hash Table +1
2281Sum of Total Strength of WizardsHardStack, Array, Prefix Sum +1
2296Design a Text EditorHardStack, Design, Linked List +3
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
2444Count Subarrays With Fixed BoundsHardQueue, Array, Sliding Window +1
2454Next Greater Element IVHardStack, Array, Binary Search +3
2524Maximum Frequency Score of a SubarrayPremiumHardStack, Array, Hash Table +2
2528Maximize the Minimum Powered CityHardGreedy, Queue, Array +3
2534Time Taken to Cross the DoorPremiumHardQueue, Array, Simulation
2589Minimum Time to Complete All TasksHardStack, Greedy, Array +2
2617Minimum Number of Visited Cells in a GridHardStack, Breadth-First Search, Union Find +5
2736Maximum Sum QueriesHardStack, Binary Indexed Tree, Segment Tree +4
2751Robot CollisionsHardStack, Array, Sorting +1
2813Maximum Elegance of a K-Length SubsequenceHardStack, Greedy, Array +3
2818Apply Operations to Maximize ScoreHardStack, Greedy, Array +4
2940Find Building Where Alice and Bob Can MeetHardStack, Binary Indexed Tree, Segment Tree +4
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.

Stack pattern FAQ

What is the stack pattern?

A stack is the right structure whenever the most recent unresolved item is the one a new element interacts with — which is another way of saying the input is nested.

How many LeetCode problems use the stack pattern?

This page lists 194 LeetCode problems that the stack pattern applies to: 26 Easy, 107 Medium and 61 Hard. 154 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the stack pattern?

O(n) time and O(n) space. A single pass that pushes and pops each token at most once. The stack grows to the maximum nesting depth, which is n for an input that opens everything before closing anything, so the worst-case space is linear even when the typical case is shallow. Rewriting a recursion with an explicit stack changes neither figure — it moves the same frames off the call stack, which is usually the entire point.

When should I use the stack pattern in an interview?

The input nests: brackets, tags, paths, expressions, nested encodings. A new element resolves against the most recent unmatched one rather than the oldest.

Which stack problem should I start with?

LeetCode 20. Valid Parentheses 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 stack?

Monotonic Stack, Tree Traversal, Depth-First Search, Linked List. 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 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.