Stacks
How a stack works, why push and pop take constant time, how to recognise stack problems such as bracket matching, and what interviewers ask.
On this page
A stack is a collection where you can only add or remove items at one end, called the top, so the item added last is the first one removed. This order is called last in, first out (LIFO). A stack is the right tool when the most recently started piece of work must be finished before any older one, which is the case for nested structures such as brackets, function calls and undo history.
Without a stack, a program that has to remember what is still open would need to search its history each time. With a stack, the answer is always at the top, so finding it takes constant time.
How a stack works
A stack has three operations, and each takes O(1) time:
- push puts an item on top.
- pop removes the top item and returns it.
- peek returns the top item without removing it.
You rarely need a special class, because the end of an array works as the top: nothing has to shift when you add or remove there. In JavaScript you use push, pop and stack[stack.length - 1] to peek. In Python you use append, pop and stack[-1]. Push is amortized O(1), because the array occasionally has to grow and copy itself, but the average cost per push stays constant.
Example: checking that brackets match
A code editor has to tell whether {x: [1, (2)]} is valid and ([)] is not. In the second text the [ opened after the (, so it has to close first.
The check reads the text from left to right. Every opener is pushed onto the stack. When a closer appears, its partner must be the most recent opener that is still unclosed, which is the top of the stack, so the check pops it and compares the two.
for each character ch: if ch is an opener: push ch else if ch is a closer: if stack is empty: return false if pop() is not ch's partner: return falsereturn stack is empty- text0(1[2]3{4}5)stack (top on the right)
1The stack starts empty, and the character pointer is at the start of the text.
- text0(ch1[2]3{4}5)stack (top on the right)0(
2
(is an opener, so it is pushed and waits for its). - text0(1[ch2]3{4}5)stack (top on the right)0(1[
3
[is an opener that starts inside the(, so it is pushed on top of it. - text0(1[2]ch3{4}5)stack (top on the right)0(
4
]is a closer, so the top is popped. It is[, which matches. - text0(1[2]3{ch4}5)stack (top on the right)0(1{
5
{is an opener, so it is pushed. - text0(1[2]3{4}ch5)stack (top on the right)0(
6
}is a closer, so the top is popped. It is{, which matches. - text0(1[2]3{4}5)chstack (top on the right)
7
)is a closer, so the top is popped. It is(, which matches. - text0(1[2]3{4}5)stack (top on the right)
- result
- true
- stack operations
- 6
8The text has ended and the stack is empty, so every opener was closed in the right order. The text is balanced, and it took six stack operations.
The check can fail in three ways. A closer can arrive when the stack is empty, as in ()), because it closes nothing. A closer can differ from the popped opener, as in ([)], because the order is wrong. Or openers can remain on the stack at the end, as in ((, because they were never closed.
const PAIRS = { ")": "(", "]": "[", "}": "{" };
function isBalanced(text) {
const stack = [];
for (const ch of text) {
if (ch === "(" || ch === "[" || ch === "{") {
stack.push(ch); // an opener waits for its closer
} else if (ch in PAIRS) {
if (stack.length === 0) return false; // closes nothing
if (stack.pop() !== PAIRS[ch]) return false; // wrong kind
}
}
return stack.length === 0; // anything left was never closed
}
isBalanced("{x: [1, (2)]}"); // true
isBalanced("([)]"); // falsePAIRS = {")": "(", "]": "[", "}": "{"}
def is_balanced(text):
stack = []
for ch in text:
if ch in "([{":
stack.append(ch) # an opener waits for its closer
elif ch in PAIRS:
if not stack:
return False # closes nothing
if stack.pop() != PAIRS[ch]:
return False # wrong kind
return not stack # anything left was never closed
is_balanced("{x: [1, (2)]}") # True
is_balanced("([)]") # False| Approach | Time | Space | Why |
|---|---|---|---|
| push, pop, peek | O(1) | O(1) | All three work at the end of the array. Push is amortized O(1). |
| Bracket check | O(n) | O(n) | Each character costs one O(1) stack step, and in the worst case, such as ((((, every character is on the stack. |
Run the bracket check by hand on [(]). Write down the stack after each character, and the character where the check returns false.
Show a sample answer
After [ the stack holds [. After ( it holds [ (, with ( on top. The next character, ], pops (, but a ] needs a [, so the check returns false at index 2. The final ) is never read, because nothing that follows can repair the order.
Variants
Array stack and linked-list stack
An array-backed stack uses the end of the array as the top, and a linked-list stack uses the head of a linked list as the top. Both give O(1) push and pop. The array version is simpler and uses less memory per item, and its push is amortized O(1) because of occasional resizing. The linked-list version has no resizing, so every push is O(1) in the worst case, but each item carries a pointer. In an interview you almost always use the built-in list or array.
Stack that also tracks a minimum
A common request is a stack that supports push, pop and getMin in O(1). A plain stack cannot do this, because after the minimum is popped you would have to scan for the next one. The fix is to store a pair with every item: the value, and the smallest value in the stack at the moment it was pushed. The pair at the top then always holds the current minimum, and popping restores the previous minimum automatically. The same idea works for a maximum.
Stack in place of recursion
Recursion already uses a stack, the call stack, where each call is pushed and each return pops it (see Recursion). If the recursion would go so deep that it overflows, you can write the same algorithm as a loop that keeps the pending work on your own stack. Depth-first search is the standard example: it keeps the places still to visit on a stack and always continues from the most recent one.
Monotonic stack
A monotonic stack pops items that break an increasing or decreasing order before each push. It finds the next larger or smaller value for every element in one pass, which a plain stack cannot do.
When a stack does not apply
A stack gives you only the newest item. If the oldest item must be handled first, as in a waiting line or in breadth-first search, you need a queue (see Queues and Deques). If you need to look up an item by position or by value, a stack is the wrong structure, because reaching anything below the top means popping everything above it.
Pitfalls
In the interview
Look for these signals in the problem statement. The problem has nested or paired structure, such as brackets, tags, quotes or an expression with parentheses. It asks you to undo, reverse or backtrack the most recent step. It asks for the "next greater" or "previous smaller" element for each position, which points to a monotonic stack. Or it asks you to evaluate an expression or to simulate recursion without recursion. In each case the question you keep asking is "what is the most recent thing that is still open?", and a stack answers it in O(1).
Questions to expect:
- "What is the time and space complexity of the bracket check?" Time is O(n), because each character causes at most one push and one pop. Space is O(n) in the worst case, when the text is all openers. If the text contains only one kind of bracket, a counter reduces the space to O(1).
- "Design a stack that returns the minimum in O(1)." Store with each item the minimum of the stack at the time it was pushed. The top item then holds the current minimum, and a pop restores the previous one. This uses O(n) extra space and no extra time.
- "Implement a queue using two stacks." Push new items onto an input stack. When you need to dequeue and the output stack is empty, pop everything from the input stack onto the output stack, which reverses the order, and pop from the output stack. Each item moves at most once, so dequeue is amortized O(1).
- "Evaluate a postfix expression such as
3 4 + 2 *." Push numbers. When you read an operator, pop two numbers, apply it and push the result. After3 4 +the stack holds 7, and after2 *it holds 14. - "Convert this recursive function to an iterative one." Push the pending calls, with their arguments, onto your own stack, and loop while it is not empty. Pop one, process it and push the calls it would have made. The order you push the children decides the visiting order, because the last one pushed is processed first.
- "How would you change the bracket check to report where the first error is, or to find the longest valid stretch?" Push the index of each opener instead of the character. A mismatch or an unmatched closer is then reported at the current index, and an opener left on the stack is reported at its stored index. For the longest valid stretch, the index under the top of the stack marks where the current valid stretch begins, so the length is the current index minus that value.
- "What is a stack overflow?" The call stack has a fixed size, and recursion that goes too deep, or never stops, fills it. The fixes are a correct base case, a smaller recursion depth, or an explicit stack on the heap.
Start with an empty stack. Push 4, push 9, pop, push 1, push 6, pop. What is on top now?
Which text makes the bracket check fail only at the final step, when it tests whether the stack is empty?
You implement a stack with a Python list, using insert(0, x) to push and pop(0) to pop. The results are correct. What is wrong with it?
What to practise next
Practise on Nesting Gift Boxes and Vintage Calculator Tape. Then read Queues and Deques for first-in, first-out order, and Monotonic Stack for finding the next larger value of every item in one pass.