First published on CodeKairo, where the figures in this lesson are animated step by step.
In short: A stack is a collection where the last item added is the first one removed — last in, first out (LIFO). It supports push (add on top), pop (remove the top) and peek (read the top), each in O(1) time, usually on a dynamic array. Stacks solve problems where the most recent unfinished item must be dealt with first: brackets, expressions, undo.
A stack is a pile: you add items on top and take them off the top, so the last item put on is the first one back. That rule is last in, first out, or LIFO. It sounds like a limitation, but it is exactly the order a whole family of problems needs: the bracket opened most recently must be closed first, the function called most recently must return first, and undo takes back the newest edit.
Why last in, first out
Is a string of brackets such as {[()]}([)] correctly nested? Counting is not enough: ([)] has one of each, yet the pairs cross. Deleting adjacent matching pairs until none are left works, but a deeply nested string loses one pair per O(n) sweep — around 5 × 10⁹ steps for n = 100,000. The insight is that a closer may only match the most recent opener not yet matched, and "most recent first" is a stack.
Figure: Why brackets need last in, first out
Draw an arc between each pair of partners. In "{[()]}" the arcs nest, so every closer meets the most recent bracket still open: exactly the top of a stack. In "([)]" the arcs cross — ')' arrives while '[' is the most recent open bracket — and that crossing is what the stack rejects.
The same shape appears whenever work is nested or interrupted: an inner expression before the outer one, a call before its caller, the newest edit before older ones.
How a stack is stored
The usual implementation is a dynamic array plus a count, with the bottom at index 0 and the top in the last used slot. Push, pop and peek each touch that one slot, which is why they are O(1).
Figure: Push, pop and peek on an array-backed stack — push 4, push 7, push 2, pop, push 9, peek
- The usual stack is an array plus a count, size. The bottom is index 0 and the top is the last used slot, data[size − 1]; the slots past size are free.
- push 4 writes data[0] = 4 and adds one to size. No other slot is touched.
- push 7 writes data[1] = 7, one past the old top, and size becomes 2. Nothing below moves, which is why push is O(1).
- push 2 writes data[2] = 2, one past the old top, and size becomes 3. Nothing below moves, which is why push is O(1).
- pop subtracts one from size and returns data[2] = 2. The 2 is still in memory, but it is past size, so it no longer counts; the next push simply writes over it.
- push 9 writes into data[2], over the stale value the pop left there. Still one write and one increment, whatever the size: O(1).
- peek reads data[size − 1] = 9 and changes nothing. Push, pop and peek each touch one slot at the end, the one place an array can change cheaply.
▶ Watch this figure animated, step by step
When the array is full, it is replaced by one a constant factor larger and everything is copied across. That push costs O(n), but the copies are rare enough that a push is O(1) amortised: constant on average over any sequence.
Figure: What 16 pushes cost when the array doubles as it fills
Most pushes write one slot. A push that finds the array full first copies everything into one twice the size — 1, 2, 4 and 8 elements, at pushes 2, 3, 5 and 9. The copies double each time but get rarer just as fast, so they add up to less than n: 31 writes for 16 pushes, O(1) amortised.
A stack can also be a linked list whose head is the top: O(1) in the worst case, but every push allocates a node, so the array is usually faster.
The operations and their cost
Push, pop, peek and the size check are all O(1); searching for a value is O(n). A stack offers nothing else on purpose.
| Language | Stack type | push | pop | peek | empty? |
|---|---|---|---|---|---|
| C++ | std::stack<T> or std::vector<T> | push(x) / push_back(x) | pop() / pop_back() | top() / back() | empty() |
| Java | Deque<T> s = new ArrayDeque<>() | push(x) | pop() | peek() | isEmpty() |
| Python | list | append(x) | pop() | s[-1] | not s |
| JavaScript | Array | push(x) | pop() | s[s.length - 1] | s.length === 0 |
In C++, pop() returns nothing, so read top() first. In Java, use ArrayDeque: the old java.util.Stack takes a lock on every call and lets code index into the middle. In Python never use pop(0), which shifts every element, and in JavaScript remember that pop() on an empty array quietly returns undefined.
The call stack
You have used a stack in every program you have written. Each function call pushes a stack frame holding its arguments, local variables and the place to return to; each return pops it.
Figure: The call stack while fact(3) runs — fact(3)
- main is running and calls fact(3). A call pushes a stack frame holding the function's arguments, its local variables and where to return to.
- fact(3) gets its own frame on top of main's. main waits underneath, its work unfinished, until this call returns.
- fact(3) cannot finish until it knows fact(2), so it calls it: one more frame on top, with its own n = 2.
- fact(1) is pushed on top. It is the base case, so it can return without calling anything: the top frame is the first to finish.
- fact(1) returns 1 and its frame is popped. fact(2) is on top again, exactly where it left off, and can now finish: 2 × 1 = 2.
- fact(2) returns 2 and its frame is popped. fact(3) is on top again, exactly where it left off, and can now finish: 3 × 2 = 6.
- fact(3) returns 6 to main, the last frame popped before main itself. The newest call always finished first: last in, first out, which is why too deep a recursion overflows this stack.
The call stack has a fixed size, so recursion 100,000 levels deep can overflow it (Python stops at about 1,000). Any recursive algorithm can push and pop its own stack in heap memory instead — see Recursion and Depth-First Search.
Matching brackets: valid parentheses
Valid Parentheses is the stack's signature problem. Read the string left to right with a stack of openers still waiting for a partner:
- An opener is pushed.
- A closer must match the opener on top. An empty stack or a different opener means invalid; otherwise pop.
- At the end the stack must be empty; anything left was never closed.
▶ The step-by-step walkthrough for this topic is on CodeKairo.
Why the top is the only candidate
If ) arrives while [ is on top, could it close a ( deeper down? No: the [ was opened inside that ( and must close first. So the invariant is: after each character, the stack holds exactly the unmatched openers, oldest at the bottom. Every push or pop keeps it, and the string is valid exactly when the stack ends empty with no closer rejected. Each character is pushed and popped at most once: O(n) time and space.
The code
The program checks five strings: two valid, one with crossing pairs, one with an opener never closed and one with a closer that has nothing to close.
C++
#include <iostream> #include <stack> #include <string> #include <vector> using namespace std; // The opener a closing bracket must match, or 0 if c is not a closer. char openerFor(char c) { if (c == ')') return '('; if (c == ']') return '['; if (c == '}') return '{'; return 0; } bool isValid(const string& s) { stack<char> openers; // openers still waiting for their partner for (char c : s) { char need = openerFor(c); if (need == 0) { openers.push(c); // an opener: wait on the stack } else { if (openers.empty() || openers.top() != need) return false; // nothing to close, or pairs cross openers.pop(); // matched the most recent opener } } return openers.empty(); // anything left was never closed } int main() { vector<string> tests = {"()[]{}", "{[()]}", "{[()]}([)]", "(()", "())"}; for (const string& s : tests) { cout << s << " -> " << (isValid(s) ? "valid" : "invalid") << "\n"; } return 0; } Java
import java.util.ArrayDeque; import java.util.Deque; public class Main { // The opener a closing bracket must match, or 0 if c is not a closer. static char openerFor(char c) { if (c == ')') return '('; if (c == ']') return '['; if (c == '}') return '{'; return 0; } static boolean isValid(String s) { Deque<Character> openers = new ArrayDeque<>(); // openers still waiting for their partner for (char c : s.toCharArray()) { char need = openerFor(c); if (need == 0) { openers.push(c); // an opener: wait on the stack } else { if (openers.isEmpty() || openers.peek() != need) return false; // nothing to close, or pairs cross openers.pop(); // matched the most recent opener } } return openers.isEmpty(); // anything left was never closed } public static void main(String[] args) { String[] tests = {"()[]{}", "{[()]}", "{[()]}([)]", "(()", "())"}; for (String s : tests) { System.out.println(s + " -> " + (isValid(s) ? "valid" : "invalid")); } } } Python
OPENER_FOR = {")": "(", "]": "[", "}": "{"} # the opener each closer must match def is_valid(s): openers = [] # openers still waiting for their partner for c in s: need = OPENER_FOR.get(c) if need is None: openers.append(c) # an opener: wait on the stack else: if not openers or openers[-1] != need: return False # nothing to close, or the pairs cross openers.pop() # matched the most recent opener return not openers # anything left was never closed tests = ["()[]{}", "{[()]}", "{[()]}([)]", "(()", "())"] for s in tests: print(f"{s} -> {'valid' if is_valid(s) else 'invalid'}") JavaScript
const OPENER_FOR = { ")": "(", "]": "[", "}": "{" }; // the opener each closer must match function isValid(s) { const openers = []; // openers still waiting for their partner for (const c of s) { const need = OPENER_FOR[c]; if (need === undefined) { openers.push(c); // an opener: wait on the stack } else { if (openers.length === 0 || openers[openers.length - 1] !== need) return false; // nothing to close, or pairs cross openers.pop(); // matched the most recent opener } } return openers.length === 0; // anything left was never closed } const tests = ["()[]{}", "{[()]}", "{[()]}([)]", "(()", "())"]; for (const s of tests) { console.log(`${s} -> ${isValid(s) ? "valid" : "invalid"}`); } Output
()[]{} -> valid {[()]} -> valid {[()]}([)] -> invalid (() -> invalid ()) -> invalid Evaluating postfix expressions
In postfix notation, or reverse Polish notation (RPN), the operator comes after its operands: 2 1 + 3 * is (2 + 1) × 3. It needs no brackets and no precedence, because the order of the tokens is the order of the work. A number is pushed; an operator pops two values and pushes the result; the one value left is the answer.
Figure: Evaluating a postfix expression with a stack — 4 13 5 / +
- Postfix puts each operator after its operands, so the order of the tokens is the order of the work and no brackets are needed. Read left to right with a stack of values.
- 4 is a number, so it is pushed. Numbers wait on the stack until an operator needs them.
- 13 is a number: push it. The top of the stack is always the most recent value not yet used.
- 5 is a number: push it. The top of the stack is always the most recent value not yet used.
- '/' applies to the two most recent unused values, the top two. The first pop is the right operand b = 5, the second the left operand a = 13 — backwards for '-' and '/', which is the classic bug.
- 13 / 5 = 2, truncated towards zero, is pushed back: the sub-expression "13 5 /" has collapsed into one value, and the rest of the expression treats it like any number.
- '+' applies to the two most recent unused values, the top two. The first pop is the right operand b = 2, the second the left operand a = 4 — backwards for '-' and '/', which is the classic bug.
- 4 + 2 = 6 is pushed, the tokens are used up, and the one value left is the answer, 6. Each token is pushed or popped a constant number of times: O(n).
The code
The third expression divides 6 by −132, which catches Python and JavaScript: Evaluate Reverse Polish Notation truncates towards zero, giving 0 and a final answer of 22, but Python's // floors to −1 and JavaScript's / gives a fraction. So Python uses int(a / b) and JavaScript Math.trunc; C++ and Java already truncate.
C++
#include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; int evalRPN(const string& expr) { vector<int> stack; istringstream in(expr); string tok; while (in >> tok) { if (tok == "+" || tok == "-" || tok == "*" || tok == "/") { int b = stack.back(); stack.pop_back(); // the right operand is on top int a = stack.back(); stack.pop_back(); if (tok == "+") stack.push_back(a + b); else if (tok == "-") stack.push_back(a - b); else if (tok == "*") stack.push_back(a * b); else stack.push_back(a / b); // C++ integer division truncates towards zero } else { stack.push_back(stoi(tok)); // a number, possibly negative such as -11 } } return stack.back(); } int main() { vector<string> tests = {"2 1 + 3 *", "4 13 5 / +", "10 6 9 3 + -11 * / * 17 + 5 +"}; for (const string& expr : tests) cout << expr << " = " << evalRPN(expr) << "\n"; return 0; } Java
import java.util.ArrayDeque; import java.util.Deque; public class Main { static int evalRPN(String expr) { Deque<Integer> stack = new ArrayDeque<>(); for (String tok : expr.split(" ")) { if (tok.equals("+") || tok.equals("-") || tok.equals("*") || tok.equals("/")) { int b = stack.pop(); // the right operand is on top int a = stack.pop(); if (tok.equals("+")) stack.push(a + b); else if (tok.equals("-")) stack.push(a - b); else if (tok.equals("*")) stack.push(a * b); else stack.push(a / b); // Java integer division truncates towards zero } else { stack.push(Integer.parseInt(tok)); // a number, possibly negative such as -11 } } return stack.pop(); } public static void main(String[] args) { String[] tests = {"2 1 + 3 *", "4 13 5 / +", "10 6 9 3 + -11 * / * 17 + 5 +"}; for (String expr : tests) System.out.println(expr + " = " + evalRPN(expr)); } } Python
def eval_rpn(expr): stack = [] for tok in expr.split(): if tok in ("+", "-", "*", "/"): b = stack.pop() # the right operand is on top a = stack.pop() if tok == "+": stack.append(a + b) elif tok == "-": stack.append(a - b) elif tok == "*": stack.append(a * b) else: stack.append(int(a / b)) # truncate towards zero; a // b would floor else: stack.append(int(tok)) # a number, possibly negative such as -11 return stack.pop() tests = ["2 1 + 3 *", "4 13 5 / +", "10 6 9 3 + -11 * / * 17 + 5 +"] for expr in tests: print(f"{expr} = {eval_rpn(expr)}") JavaScript
function evalRPN(expr) { const stack = []; for (const tok of expr.split(" ")) { if (tok === "+" || tok === "-" || tok === "*" || tok === "/") { const b = stack.pop(); // the right operand is on top const a = stack.pop(); if (tok === "+") stack.push(a + b); else if (tok === "-"Source:https://dev.to/codekairo/stack-data-structure-lifo-operations-and-patterns-1ie2