Pattern 05 of 22

Stack Pattern: Template + 194 LeetCode Problems

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

Easy
26
Medium
107
Hard
61
Time
O(n)

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.

PythonStack 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.

Eyes only

Meet the 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 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)

Easy problems
No.Problem
0020Valid Parentheses
0094Binary Tree Inorder Traversal
0144Binary Tree Preorder Traversal
0145Binary Tree Postorder Traversal
0225Implement Stack using Queues
0232Implement Queue using Stacks
0234Palindrome Linked List
0387First Unique Character in a String
0496Next Greater Element I
0589N-ary Tree Preorder Traversal
0590N-ary Tree Postorder Traversal
0682Baseball Game
0933Number of Recent Calls
0346Moving Average from Data StreamPremium
0844Backspace String Compare
0897Increasing Order Search Tree
1021Remove Outermost Parentheses
1047Remove All Adjacent Duplicates In String
1475Final Prices With a Special Discount in a Shop
1544Make The String Great
1598Crawler Log Folder
1614Maximum Nesting Depth of the Parentheses
1700Number of Students Unable to Eat Lunch
2000Reverse Prefix of Word
2073Time Needed to Buy Tickets
2696Minimum String Length After Removing Substrings

Medium (107)

Medium problems
No.Problem
0071Simplify Path
0114Flatten Binary Tree to Linked List
0143Reorder List
0150Evaluate Reverse Polish Notation
0155Min Stack
0173Binary Search Tree Iterator
0227Basic Calculator II
0316Remove Duplicate Letters
0331Verify Preorder Serialization of a Binary Tree
0341Flatten Nested List Iterator
0385Mini Parser
0388Longest Absolute File Path
0394Decode String
0402Remove K Digits
0445Add Two Numbers II
0456132 Pattern
0503Next Greater Element II
0581Shortest Unsorted Continuous Subarray
0622Design Circular Queue
0636Exclusive Time of Functions
0641Design Circular Deque
0649Dota2 Senate
0654Maximum Binary Tree
0678Valid Parenthesis String
0735Asteroid Collision
0739Daily Temperatures
0853Car Fleet
0901Online Stock Span
0918Maximum Sum Circular Subarray
2130Maximum Twin Sum of a Linked List
2390Removing Stars From a String
0255Verify Preorder Sequence in Binary Search TreePremium
0281Zigzag IteratorPremium
0353Design Snake GamePremium
0362Design Hit CounterPremium
0364Nested List Weight Sum IIPremium
0379Design Phone DirectoryPremium
0426Convert Binary Search Tree to Sorted Doubly Linked ListPremium
0439Ternary Expression ParserPremium
0484Find PermutationPremium
0536Construct Binary Tree from StringPremium
0769Max Chunks To Make Sorted
0856Score of Parentheses
0880Decoded String at Index
0907Sum of Subarray Minimums
0921Minimum Add to Make Parentheses Valid
0946Validate Stack Sequences
0950Reveal Cards In Increasing Order
0962Maximum Width Ramp
1003Check If Word Is Valid After Substitutions
1006Clumsy Factorial
1008Construct Binary Search Tree from Preorder Traversal
1019Next Greater Node In Linked List
1081Smallest Subsequence of Distinct Characters
1087Brace ExpansionPremium
1111Maximum Nesting Depth of Two Valid Parentheses Strings
1124Longest Well-Performing Interval
1130Minimum Cost Tree From Leaf Values
1190Reverse Substrings Between Each Pair of Parentheses
1209Remove All Adjacent Duplicates in String II
1214Two Sum BSTsPremium
1249Minimum Remove to Make Valid Parentheses
1265Print Immutable Linked List in ReversePremium
1381Design a Stack With Increment Operation
1429First Unique NumberPremium
1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
1441Build an Array With Stack Operations
1472Design Browser History
1504Count Submatrices With All Ones
1541Minimum Insertions to Balance a Parentheses String
1574Shortest Subarray to be Removed to Make Array Sorted
1586Binary Search Tree Iterator IIPremium
1628Design an Expression Tree With Evaluate FunctionPremium
1653Minimum Deletions to Make String Balanced
1670Design Front Middle Back Queue
1673Find the Most Competitive Subsequence
1696Jump Game VI
1717Maximum Score From Removing Substrings
1762Buildings With an Ocean ViewPremium
1823Find the Winner of the Circular Game
1856Maximum Subarray Min-Product
1910Remove All Occurrences of a Substring
1950Maximum of Minimum Values in All SubarraysPremium
1963Minimum Number of Swaps to Make the String Balanced
1996The Number of Weak Characters in the Game
2104Sum of Subarray Ranges
2116Check if a Parentheses String Can Be Valid
2211Count Collisions on a Road
2216Minimum Deletions to Make Array Beautiful
2282Number of People That Can Be Seen in a GridPremium
2289Steps to Make Array Non-decreasing
2297Jump Game VIIIPremium
2327Number of People Aware of a Secret
2345Finding the Number of Visible MountainsPremium
2375Construct Smallest Number From DI String
2434Using a Robot to Print the Lexicographically Smallest String
2487Remove Nodes From Linked List
2526Find Consecutive Integers from a Data Stream
2645Minimum Additions to Make Valid String
2762Continuous Subarrays
2764Is Array a Preorder of Some ‌Binary TreePremium
2816Double a Number Represented as a Linked List
2832Maximal Range That Each Element Is Maximum in ItPremium
2863Maximum Length of Semi-Decreasing SubarraysPremium
2865Beautiful Towers I
2866Beautiful Towers II
2944Minimum Number of Coins for Fruits

Hard (61)

Hard problems
No.Problem
0032Longest Valid Parentheses
0042Trapping Rain Water
0084Largest Rectangle in Histogram
0085Maximal Rectangle
0224Basic Calculator
0239Sliding Window Maximum
0321Create Maximum Number
0488Zuma Game
0591Tag Validator
0736Parse Lisp Expression
0272Closest Binary Search Tree Value IIPremium
0683K Empty SlotsPremium
0716Max StackPremium
0726Number of Atoms
0768Max Chunks To Make Sorted II
0770Basic Calculator IV
0772Basic Calculator IIIPremium
0862Shortest Subarray with Sum at Least K
0895Maximum Frequency Stack
0936Stamping The Sequence
0975Odd Even Jump
0995Minimum Number of K Consecutive Bit Flips
1063Number of Valid SubarraysPremium
1096Brace Expansion II
1106Parsing A Boolean Expression
1172Dinner Plate Stacks
1425Constrained Subsequence Sum
1499Max Value of Equation
1526Minimum Number of Increments on Subarrays to Form a Target Array
1597Build Binary Expression Tree From Infix ExpressionPremium
1687Delivering Boxes from Storage to Ports
1776Car Fleet II
1793Maximum Score of a Good Subarray
1825Finding MK Average
1896Minimum Cost to Change the Final Value of Expression
1944Number of Visible People in a Queue
2019The Score of Students Solving Math Expression
2030Smallest K-Length Subsequence With Occurrences of a Letter
2071Maximum Number of Tasks You Can Assign
2197Replace Non-Coprime Numbers in Array
2254Design Video Sharing PlatformPremium
2281Sum of Total Strength of Wizards
2296Design a Text Editor
2334Subarray With Elements Greater Than Varying Threshold
2355Maximum Number of Books You Can TakePremium
2398Maximum Number of Robots Within Budget
2407Longest Increasing Subsequence II
2444Count Subarrays With Fixed Bounds
2454Next Greater Element IV
2524Maximum Frequency Score of a SubarrayPremium
2528Maximize the Minimum Powered City
2534Time Taken to Cross the DoorPremium
2589Minimum Time to Complete All Tasks
2617Minimum Number of Visited Cells in a Grid
2736Maximum Sum Queries
2751Robot Collisions
2813Maximum Elegance of a K-Length Subsequence
2818Apply Operations to Maximize Score
2940Find Building Where Alice and Bob Can Meet
2945Find Maximum Non-decreasing Array Length
2969Minimum Number of Coins for Fruits IIPremium

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.