Pattern · Interview prep
Stack
Remember unfinished work in last-in, first-out order. Push when something opens, and pop when a later item resolves it.
What it is
What is the stack pattern?
A stack keeps the items that are still open, with the newest one on top. You push when you start something, and you pop when a later item closes it. The match is always the most recent unmatched item, not an earlier one and not a count of how many you have seen.
- Matching closers. Push each opener. A closer must equal the top. An empty stack at the end means every opener was closed.
- Monotonic stack. Keep indexes whose values are still waiting. Pop while the new value resolves them, then push the current index.
When to use it
How do you recognize a stack problem?
Read the statement for these signals before you scan for the nearest match from scratch.
Read the full recognition guide: Stack clues: matching, next greater, and undo
Phrases to watch for
- matching brackets
- nested
- most recent unmatched
- next warmer
- previous greater
- undo
- postfix
- 1
A later item closes an earlier one
Brackets, tags, or nested spans. The partner is the opener that is still open, not the first opener in the string.
- 2
You need the nearest waiting value
The next warmer minute, or the previous greater value, can resolve several indexes at once. Those indexes were stored in order.
- 3
Work has to unwind in reverse
An operator applies to the two most recent values. The later value is on the right.
Looks similar, but isn’t
The next item to handle is the oldest
A queue serves arrivals in order. A stack serves the newest open item. Building a queue from two stacks is a separate exercise.
The answer is a contiguous slice
Sliding Window grows and shrinks a range. A stack remembers nested or waiting items, not a moving sum.
You are comparing both ends of a sorted row
Two Pointers walks the ends. A palindrome can be reversed onto a stack, but the inward pointers do that comparison in place.
Worked example
How does it work on matching brackets?
The string contains only parentheses, brackets, and braces. Return true when every closer matches the most recent unmatched opener, and every opener is closed by the end. An empty string is balanced. This is the classic stack, and one of the problems you can practice below.
function isBalanced(text: string): boolean { const openByClose: Record<string, string> = { ')': '(', ']': '[', '}': '{' }; const stack: string[] = []; for (const symbol of text) { const opener = openByClose[symbol]; if (opener === undefined) { stack.push(symbol); continue; } // A closer must match the most recent opener. if (stack.pop() !== opener) return false; } return stack.length === 0;}The closer is compared with the top, then the top is removed.
Code is shown in TypeScript. You can solve problems in TypeScript, JavaScript, or Python.
Complexity
- TimeO(n)
Each symbol is pushed once or popped once.
- SpaceO(n)
The stack holds the openers that are still unmatched. That can be the whole string.
An empty string
Nothing was opened, so nothing is left unmatched. The stack stays empty and the result is true.
The next warmer minute
Store indexes, not temperatures. While the current reading is strictly warmer than the top, pop that index and record the distance. Then push the current index. Equal is not warmer.
Step by step on ([])
- 1
The first symbol is
(. It is an opener, so push it. The stack is(.(L·R[]) - 2
[is another opener. Push it. The stack is(, then[on top.([L·R]) - 3
]is a closer. The top is[, which matches, so pop it. The stack is(again.([L]R) - 4
)matches the remaining(. Pop it. The stack is empty, so the string is balanced.([])
Common mistakes
What mistakes do people make with stack?
Popping until the stack is empty
A closer matches only the top. Clearing the whole stack throws away openers that are still waiting.
InsteadPop once, compare that value with the closer, and stop. Later closers will meet the items underneath.
Ignoring what is left at the end
A string of only openers never fails a closer check. It is still unbalanced.
InsteadAfter the scan, the stack must be empty. Leftover openers mean false.
A closer when nothing is open
Popping an empty stack has no partner. Treating that as a skip, or as a match, accepts a string that starts with a closer.
InsteadIf the stack is empty when a closer arrives, return false immediately.
Storing values when the answer needs indexes
A warmer-minute answer is how many steps passed. Temperatures alone do not give that distance.
InsteadPush indexes. The distance is the current index minus the index you just popped.
Practice it in Algofily
Which Algofily problems train stack?
4 problems are tagged Stack. They run from matching brackets and a warmer-minute scan to a queue built from two stacks.
- Locked: opens after you create an account. Balanced SymbolseasyStackA string contains only parentheses, brackets, and braces: ()[]{}.Algofily 40Open problem
- Locked: opens after you create an account. Next Warmer ReadingmediumStackA sensor writes one temperature each minute.Algofily 40Open problem
- Locked: opens after you create an account. Queue From Two StackseasyStack · QueueSimulate a queue using two stacks.Algofily 40Open problem
- Locked: opens after you create an account. Postfix CalculatormediumStackEvaluate a postfix expression.Algofily 40Open problem
A lock means the problem opens after you create an account. Pair With Target is open to try without one.
Start Learning.
Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.