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.
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 unbalancedComplexity 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.
Easy (26)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 20 | Valid Parentheses | Easy | Stack, String |
| 94 | Binary Tree Inorder Traversal | Easy | Stack, Tree, Depth-First Search +1 |
| 144 | Binary Tree Preorder Traversal | Easy | Stack, Tree, Depth-First Search +1 |
| 145 | Binary Tree Postorder Traversal | Easy | Stack, Tree, Depth-First Search +1 |
| 225 | Implement Stack using Queues | Easy | Stack, Design, Queue |
| 232 | Implement Queue using Stacks | Easy | Stack, Design, Queue |
| 234 | Palindrome Linked List | Easy | Stack, Recursion, Linked List +1 |
| 387 | First Unique Character in a String | Easy | Queue, Hash Table, String +1 |
| 496 | Next Greater Element I | Easy | Stack, Array, Hash Table +1 |
| 589 | N-ary Tree Preorder Traversal | Easy | Stack, Tree, Depth-First Search |
| 590 | N-ary Tree Postorder Traversal | Easy | Stack, Tree, Depth-First Search |
| 682 | Baseball Game | Easy | Stack, Array, Simulation |
| 933 | Number of Recent Calls | Easy | Design, Queue, Data Stream |
| 346 | Moving Average from Data StreamPremium | Easy | Design, Queue, Array +1 |
| 844 | Backspace String Compare | Easy | Stack, Two Pointers, String +1 |
| 897 | Increasing Order Search Tree | Easy | Stack, Tree, Depth-First Search +2 |
| 1021 | Remove Outermost Parentheses | Easy | Stack, String |
| 1047 | Remove All Adjacent Duplicates In String | Easy | Stack, String |
| 1475 | Final Prices With a Special Discount in a Shop | Easy | Stack, Array, Monotonic Stack |
| 1544 | Make The String Great | Easy | Stack, String |
| 1598 | Crawler Log Folder | Easy | Stack, Array, String |
| 1614 | Maximum Nesting Depth of the Parentheses | Easy | Stack, String |
| 1700 | Number of Students Unable to Eat Lunch | Easy | Stack, Queue, Array +1 |
| 2000 | Reverse Prefix of Word | Easy | Stack, Two Pointers, String |
| 2073 | Time Needed to Buy Tickets | Easy | Queue, Array, Simulation |
| 2696 | Minimum String Length After Removing Substrings | Easy | Stack, String, Simulation |
Medium (107)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 71 | Simplify Path | Medium | Stack, String |
| 114 | Flatten Binary Tree to Linked List | Medium | Stack, Tree, Depth-First Search +2 |
| 143 | Reorder List | Medium | Stack, Recursion, Linked List +1 |
| 150 | Evaluate Reverse Polish Notation | Medium | Stack, Array, Math |
| 155 | Min Stack | Medium | Stack, Design |
| 173 | Binary Search Tree Iterator | Medium | Stack, Tree, Design +3 |
| 227 | Basic Calculator II | Medium | Stack, Math, String |
| 316 | Remove Duplicate Letters | Medium | Stack, Greedy, String +1 |
| 331 | Verify Preorder Serialization of a Binary Tree | Medium | Stack, Tree, String +1 |
| 341 | Flatten Nested List Iterator | Medium | Stack, Tree, Depth-First Search +3 |
| 385 | Mini Parser | Medium | Stack, Depth-First Search, String |
| 388 | Longest Absolute File Path | Medium | Stack, Depth-First Search, String |
| 394 | Decode String | Medium | Stack, Recursion, String |
| 402 | Remove K Digits | Medium | Stack, Greedy, String +1 |
| 445 | Add Two Numbers II | Medium | Stack, Linked List, Math |
| 456 | 132 Pattern | Medium | Stack, Array, Binary Search +2 |
| 503 | Next Greater Element II | Medium | Stack, Array, Monotonic Stack |
| 581 | Shortest Unsorted Continuous Subarray | Medium | Stack, Greedy, Array +3 |
| 622 | Design Circular Queue | Medium | Design, Queue, Array +1 |
| 636 | Exclusive Time of Functions | Medium | Stack, Array |
| 641 | Design Circular Deque | Medium | Design, Queue, Array +1 |
| 649 | Dota2 Senate | Medium | Greedy, Queue, String |
| 654 | Maximum Binary Tree | Medium | Stack, Tree, Array +3 |
| 678 | Valid Parenthesis String | Medium | Stack, Greedy, String +1 |
| 735 | Asteroid Collision | Medium | Stack, Array, Simulation |
| 739 | Daily Temperatures | Medium | Stack, Array, Monotonic Stack |
| 853 | Car Fleet | Medium | Stack, Array, Sorting +1 |
| 901 | Online Stock Span | Medium | Stack, Design, Data Stream +1 |
| 918 | Maximum Sum Circular Subarray | Medium | Queue, Array, Divide and Conquer +2 |
| 2130 | Maximum Twin Sum of a Linked List | Medium | Stack, Linked List, Two Pointers |
| 2390 | Removing Stars From a String | Medium | Stack, String, Simulation |
| 255 | Verify Preorder Sequence in Binary Search TreePremium | Medium | Stack, Tree, Binary Search Tree +4 |
| 281 | Zigzag IteratorPremium | Medium | Design, Queue, Array +1 |
| 353 | Design Snake GamePremium | Medium | Design, Queue, Array +2 |
| 362 | Design Hit CounterPremium | Medium | Design, Queue, Array +2 |
| 364 | Nested List Weight Sum IIPremium | Medium | Stack, Depth-First Search, Breadth-First Search |
| 379 | Design Phone DirectoryPremium | Medium | Design, Queue, Array +2 |
| 426 | Convert Binary Search Tree to Sorted Doubly Linked ListPremium | Medium | Stack, Tree, Depth-First Search +4 |
| 439 | Ternary Expression ParserPremium | Medium | Stack, Recursion, String |
| 484 | Find PermutationPremium | Medium | Stack, Greedy, Array +1 |
| 536 | Construct Binary Tree from StringPremium | Medium | Stack, Tree, Depth-First Search +2 |
| 769 | Max Chunks To Make Sorted | Medium | Stack, Greedy, Array +2 |
| 856 | Score of Parentheses | Medium | Stack, String |
| 880 | Decoded String at Index | Medium | Stack, String |
| 907 | Sum of Subarray Minimums | Medium | Stack, Array, Dynamic Programming +1 |
| 921 | Minimum Add to Make Parentheses Valid | Medium | Stack, Greedy, String |
| 946 | Validate Stack Sequences | Medium | Stack, Array, Simulation |
| 950 | Reveal Cards In Increasing Order | Medium | Queue, Array, Sorting +1 |
| 962 | Maximum Width Ramp | Medium | Stack, Array, Two Pointers +1 |
| 1003 | Check If Word Is Valid After Substitutions | Medium | Stack, String |
| 1006 | Clumsy Factorial | Medium | Stack, Math, Simulation |
| 1008 | Construct Binary Search Tree from Preorder Traversal | Medium | Stack, Tree, Binary Search Tree +3 |
| 1019 | Next Greater Node In Linked List | Medium | Stack, Array, Linked List +1 |
| 1081 | Smallest Subsequence of Distinct Characters | Medium | Stack, Greedy, String +1 |
| 1087 | Brace ExpansionPremium | Medium | Stack, Breadth-First Search, String +2 |
| 1111 | Maximum Nesting Depth of Two Valid Parentheses Strings | Medium | Stack, String |
| 1124 | Longest Well-Performing Interval | Medium | Stack, Array, Hash Table +2 |
| 1130 | Minimum Cost Tree From Leaf Values | Medium | Stack, Greedy, Array +2 |
| 1190 | Reverse Substrings Between Each Pair of Parentheses | Medium | Stack, String |
| 1209 | Remove All Adjacent Duplicates in String II | Medium | Stack, String |
| 1214 | Two Sum BSTsPremium | Medium | Stack, Tree, Depth-First Search +4 |
| 1249 | Minimum Remove to Make Valid Parentheses | Medium | Stack, String |
| 1265 | Print Immutable Linked List in ReversePremium | Medium | Stack, Recursion, Linked List +1 |
| 1381 | Design a Stack With Increment Operation | Medium | Stack, Design, Array |
| 1429 | First Unique NumberPremium | Medium | Design, Queue, Array +2 |
| 1438 | Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit | Medium | Queue, Array, Ordered Set +3 |
| 1441 | Build an Array With Stack Operations | Medium | Stack, Array, Simulation |
| 1472 | Design Browser History | Medium | Stack, Design, Array +3 |
| 1504 | Count Submatrices With All Ones | Medium | Stack, Array, Dynamic Programming +2 |
| 1541 | Minimum Insertions to Balance a Parentheses String | Medium | Stack, Greedy, String |
| 1574 | Shortest Subarray to be Removed to Make Array Sorted | Medium | Stack, Array, Two Pointers +2 |
| 1586 | Binary Search Tree Iterator IIPremium | Medium | Stack, Tree, Design +3 |
| 1628 | Design an Expression Tree With Evaluate FunctionPremium | Medium | Stack, Tree, Design +3 |
| 1653 | Minimum Deletions to Make String Balanced | Medium | Stack, String, Dynamic Programming |
| 1670 | Design Front Middle Back Queue | Medium | Design, Queue, Array +2 |
| 1673 | Find the Most Competitive Subsequence | Medium | Stack, Greedy, Array +1 |
| 1696 | Jump Game VI | Medium | Queue, Array, Dynamic Programming +2 |
| 1717 | Maximum Score From Removing Substrings | Medium | Stack, Greedy, String |
| 1762 | Buildings With an Ocean ViewPremium | Medium | Stack, Array, Monotonic Stack |
| 1823 | Find the Winner of the Circular Game | Medium | Recursion, Queue, Array +2 |
| 1856 | Maximum Subarray Min-Product | Medium | Stack, Array, Prefix Sum +1 |
| 1910 | Remove All Occurrences of a Substring | Medium | Stack, String, Simulation |
| 1950 | Maximum of Minimum Values in All SubarraysPremium | Medium | Stack, Array, Monotonic Stack |
| 1963 | Minimum Number of Swaps to Make the String Balanced | Medium | Stack, Greedy, Two Pointers +1 |
| 1996 | The Number of Weak Characters in the Game | Medium | Stack, Greedy, Array +2 |
| 2104 | Sum of Subarray Ranges | Medium | Stack, Array, Monotonic Stack |
| 2116 | Check if a Parentheses String Can Be Valid | Medium | Stack, Greedy, String |
| 2211 | Count Collisions on a Road | Medium | Stack, String, Simulation |
| 2216 | Minimum Deletions to Make Array Beautiful | Medium | Stack, Greedy, Array |
| 2282 | Number of People That Can Be Seen in a GridPremium | Medium | Stack, Array, Matrix +1 |
| 2289 | Steps to Make Array Non-decreasing | Medium | Stack, Array, Linked List +1 |
| 2297 | Jump Game VIIIPremium | Medium | Stack, Graph, Array +3 |
| 2327 | Number of People Aware of a Secret | Medium | Queue, Dynamic Programming, Simulation |
| 2345 | Finding the Number of Visible MountainsPremium | Medium | Stack, Array, Sorting +1 |
| 2375 | Construct Smallest Number From DI String | Medium | Stack, Greedy, String +1 |
| 2434 | Using a Robot to Print the Lexicographically Smallest String | Medium | Stack, Greedy, Hash Table +1 |
| 2487 | Remove Nodes From Linked List | Medium | Stack, Recursion, Linked List +1 |
| 2526 | Find Consecutive Integers from a Data Stream | Medium | Design, Queue, Hash Table +2 |
| 2645 | Minimum Additions to Make Valid String | Medium | Stack, Greedy, String +1 |
| 2762 | Continuous Subarrays | Medium | Queue, Array, Ordered Set +3 |
| 2764 | Is Array a Preorder of Some Binary TreePremium | Medium | Stack, Tree, Depth-First Search +1 |
| 2816 | Double a Number Represented as a Linked List | Medium | Stack, Linked List, Math |
| 2832 | Maximal Range That Each Element Is Maximum in ItPremium | Medium | Stack, Array, Monotonic Stack |
| 2863 | Maximum Length of Semi-Decreasing SubarraysPremium | Medium | Stack, Array, Sorting +1 |
| 2865 | Beautiful Towers I | Medium | Stack, Array, Monotonic Stack |
| 2866 | Beautiful Towers II | Medium | Stack, Array, Monotonic Stack |
| 2944 | Minimum Number of Coins for Fruits | Medium | Queue, Array, Dynamic Programming +2 |
Hard (61)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 32 | Longest Valid Parentheses | Hard | Stack, String, Dynamic Programming |
| 42 | Trapping Rain Water | Hard | Stack, Array, Two Pointers +2 |
| 84 | Largest Rectangle in Histogram | Hard | Stack, Array, Monotonic Stack |
| 85 | Maximal Rectangle | Hard | Stack, Array, Dynamic Programming +2 |
| 224 | Basic Calculator | Hard | Stack, Recursion, Math +1 |
| 239 | Sliding Window Maximum | Hard | Queue, Array, Sliding Window +2 |
| 321 | Create Maximum Number | Hard | Stack, Greedy, Array +2 |
| 488 | Zuma Game | Hard | Stack, Breadth-First Search, Memoization +2 |
| 591 | Tag Validator | Hard | Stack, String |
| 736 | Parse Lisp Expression | Hard | Stack, Recursion, Hash Table +1 |
| 272 | Closest Binary Search Tree Value IIPremium | Hard | Stack, Tree, Depth-First Search +4 |
| 683 | K Empty SlotsPremium | Hard | Binary Indexed Tree, Segment Tree, Queue +5 |
| 716 | Max StackPremium | Hard | Stack, Design, Linked List +2 |
| 726 | Number of Atoms | Hard | Stack, Hash Table, String +1 |
| 768 | Max Chunks To Make Sorted II | Hard | Stack, Greedy, Array +2 |
| 770 | Basic Calculator IV | Hard | Stack, Recursion, Hash Table +2 |
| 772 | Basic Calculator IIIPremium | Hard | Stack, Recursion, Math +1 |
| 862 | Shortest Subarray with Sum at Least K | Hard | Queue, Array, Binary Search +4 |
| 895 | Maximum Frequency Stack | Hard | Stack, Design, Hash Table +1 |
| 936 | Stamping The Sequence | Hard | Stack, Greedy, Queue +1 |
| 975 | Odd Even Jump | Hard | Stack, Array, Dynamic Programming +3 |
| 995 | Minimum Number of K Consecutive Bit Flips | Hard | Bit Manipulation, Queue, Array +2 |
| 1063 | Number of Valid SubarraysPremium | Hard | Stack, Array, Monotonic Stack |
| 1096 | Brace Expansion II | Hard | Stack, Breadth-First Search, Hash Table +3 |
| 1106 | Parsing A Boolean Expression | Hard | Stack, Recursion, String |
| 1172 | Dinner Plate Stacks | Hard | Stack, Design, Hash Table +1 |
| 1425 | Constrained Subsequence Sum | Hard | Queue, Array, Dynamic Programming +3 |
| 1499 | Max Value of Equation | Hard | Queue, Array, Sliding Window +2 |
| 1526 | Minimum Number of Increments on Subarrays to Form a Target Array | Hard | Stack, Greedy, Array +2 |
| 1597 | Build Binary Expression Tree From Infix ExpressionPremium | Hard | Stack, Tree, String +1 |
| 1687 | Delivering Boxes from Storage to Ports | Hard | Segment Tree, Queue, Array +4 |
| 1776 | Car Fleet II | Hard | Stack, Array, Math +2 |
| 1793 | Maximum Score of a Good Subarray | Hard | Stack, Array, Two Pointers +2 |
| 1825 | Finding MK Average | Hard | Design, Queue, Data Stream +2 |
| 1896 | Minimum Cost to Change the Final Value of Expression | Hard | Stack, Math, String +1 |
| 1944 | Number of Visible People in a Queue | Hard | Stack, Array, Monotonic Stack |
| 2019 | The Score of Students Solving Math Expression | Hard | Stack, Memoization, Array +4 |
| 2030 | Smallest K-Length Subsequence With Occurrences of a Letter | Hard | Stack, Greedy, String +1 |
| 2071 | Maximum Number of Tasks You Can Assign | Hard | Greedy, Queue, Array +4 |
| 2197 | Replace Non-Coprime Numbers in Array | Hard | Stack, Array, Math +1 |
| 2254 | Design Video Sharing PlatformPremium | Hard | Stack, Design, Hash Table +1 |
| 2281 | Sum of Total Strength of Wizards | Hard | Stack, Array, Prefix Sum +1 |
| 2296 | Design a Text Editor | Hard | Stack, Design, Linked List +3 |
| 2334 | Subarray With Elements Greater Than Varying Threshold | Hard | Stack, Union Find, Array +1 |
| 2355 | Maximum Number of Books You Can TakePremium | Hard | Stack, Array, Dynamic Programming +1 |
| 2398 | Maximum Number of Robots Within Budget | Hard | Queue, Array, Binary Search +4 |
| 2407 | Longest Increasing Subsequence II | Hard | Binary Indexed Tree, Segment Tree, Queue +4 |
| 2444 | Count Subarrays With Fixed Bounds | Hard | Queue, Array, Sliding Window +1 |
| 2454 | Next Greater Element IV | Hard | Stack, Array, Binary Search +3 |
| 2524 | Maximum Frequency Score of a SubarrayPremium | Hard | Stack, Array, Hash Table +2 |
| 2528 | Maximize the Minimum Powered City | Hard | Greedy, Queue, Array +3 |
| 2534 | Time Taken to Cross the DoorPremium | Hard | Queue, Array, Simulation |
| 2589 | Minimum Time to Complete All Tasks | Hard | Stack, Greedy, Array +2 |
| 2617 | Minimum Number of Visited Cells in a Grid | Hard | Stack, Breadth-First Search, Union Find +5 |
| 2736 | Maximum Sum Queries | Hard | Stack, Binary Indexed Tree, Segment Tree +4 |
| 2751 | Robot Collisions | Hard | Stack, Array, Sorting +1 |
| 2813 | Maximum Elegance of a K-Length Subsequence | Hard | Stack, Greedy, Array +3 |
| 2818 | Apply Operations to Maximize Score | Hard | Stack, Greedy, Array +4 |
| 2940 | Find Building Where Alice and Bob Can Meet | Hard | Stack, Binary Indexed Tree, Segment Tree +4 |
| 2945 | Find Maximum Non-decreasing Array Length | Hard | Stack, Queue, Array +4 |
| 2969 | Minimum Number of Coins for Fruits IIPremium | Hard | Queue, 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.