Stacks
Last-in, first-out. The structure behind function calls, undo, parsing and depth-first search.
A stack is a collection where you can only add (push) and remove (pop) at one end — the top. The last element pushed is the first one popped: LIFO (last in, first out). Think of a stack of plates.
Operations
| Operation | Description | Time |
|---|---|---|
push(x) | Add x on top | O(1) |
pop() | Remove & return top | O(1) |
peek() / top() | Read top without removing | O(1) |
isEmpty() | Any elements? | O(1) |
A stack is usually backed by a dynamic array (push/pop at the end) or a linked list (push/pop at the head).
import java.util.ArrayDeque;
import java.util.Deque;
// Prefer ArrayDeque over the legacy synchronized java.util.Stack
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.peek(); // 2
stack.pop(); // 2
stack.isEmpty(); // falsestack = [] # a list is a perfect stack
stack.append(1) # push
stack.append(2)
stack[-1] # peek -> 2
stack.pop() # 2
not stack # is empty? -> Falseconst stack: number[] = [];
stack.push(1);
stack.push(2);
stack[stack.length - 1]; // peek -> 2
stack.pop(); // 2
stack.length === 0; // falseWhere stacks appear
- The call stack. Each function call pushes a stack frame (locals, return address); returning pops it. Infinite recursion →
StackOverflowError. See Memory: stack & heap. - Undo / back button. Push each action; undo pops the latest.
- Parsing. Matching brackets, evaluating expressions, HTML tag matching, compilers.
- DFS. Iterative depth-first search uses an explicit stack. See Graph traversal.
- Monotonic stacks for "next greater element" style problems. See Monotonic stack.
Classic problem: valid parentheses
Push every opener; for every closer, the top of the stack must be its matching opener.
boolean isValid(String s) {
Deque<Character> st = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(') st.push(')');
else if (c == '[') st.push(']');
else if (c == '{') st.push('}');
else if (st.isEmpty() || st.pop() != c) return false;
}
return st.isEmpty();
}def is_valid(s: str) -> bool:
pairs = {')': '(', ']': '[', '}': '{'}
st = []
for c in s:
if c in pairs:
if not st or st.pop() != pairs[c]:
return False
else:
st.append(c)
return not stfunction isValid(s: string): boolean {
const pairs: Record<string, string> = { ")": "(", "]": "[", "}": "{" };
const st: string[] = [];
for (const c of s) {
if (c in pairs) {
if (st.pop() !== pairs[c]) return false;
} else st.push(c);
}
return st.length === 0;
}Classic problem: min stack
Support getMin() in O(1). Keep a second stack holding the minimum at each depth.
class MinStack {
private final Deque<int[]> st = new ArrayDeque<>(); // [value, minSoFar]
void push(int x) {
int min = st.isEmpty() ? x : Math.min(x, st.peek()[1]);
st.push(new int[]{x, min});
}
void pop() { st.pop(); }
int top() { return st.peek()[0]; }
int getMin() { return st.peek()[1]; }
}class MinStack:
def __init__(self):
self.st = [] # (value, min_so_far)
def push(self, x: int) -> None:
m = min(x, self.st[-1][1]) if self.st else x
self.st.append((x, m))
def pop(self) -> None: self.st.pop()
def top(self) -> int: return self.st[-1][0]
def get_min(self) -> int: return self.st[-1][1]class MinStack {
private st: [number, number][] = []; // [value, minSoFar]
push(x: number) {
const m = this.st.length ? Math.min(x, this.st[this.st.length - 1][1]) : x;
this.st.push([x, m]);
}
pop() { this.st.pop(); }
top() { return this.st[this.st.length - 1][0]; }
getMin() { return this.st[this.st.length - 1][1]; }
}Evaluating expressions
Postfix (Reverse Polish) notation is evaluated with one stack: push numbers; on an operator, pop two, apply, push the result. 3 4 + 2 * → 14. Infix expressions are converted to postfix with Dijkstra's shunting-yard algorithm (two stacks: operators and output).
- Stacks are LIFO with O(1) push/pop/peek.
- Use
ArrayDequein Java, a list in Python, an array in JS/TS. - Reach for a stack when the most recent unmatched item matters: brackets, undo, recursion → iteration, DFS, next-greater-element.
QImplement a queue using two stacks.medium
Push onto an in stack. To dequeue, if out is empty, pop everything from in onto out (reversing order), then pop from out. Each element moves at most twice → amortized O(1) per operation.
QWhy does deep recursion cause a stack overflow, and how do you avoid it?easy
Each call consumes a frame on a fixed-size thread stack (often ~512 KB–8 MB). Avoid it by converting the recursion to iteration with an explicit heap-allocated stack, using tail recursion where the language optimises it, or reducing depth (e.g. recurse on the smaller half in quicksort).
QDaily temperatures: for each day, how many days until a warmer one?medium
Monotonic decreasing stack of indices. For each day, pop while the top is colder than today, setting answer[popped] = today - popped, then push today. O(n).