Mental model
Think of a pile of plates. You put a plate on top and you take the top plate off; reaching into the middle is not part of the deal. A stack is a collection with exactly that rule: last in, first out (LIFO). It has three operations:
push(x): putxon top.pop(): remove the top element and return it.peek()(also calledtop): return the top element without removing it.
That is all. No search, no index access, no insertion in the middle. The restriction is the point: whenever a problem has the shape "the most recent unfinished thing must be finished first", a stack models it directly. Your program's call stack works this way: the function called last returns first. So do undo histories, browser back buttons, and the depth-first search you will meet later.
Where is the top?
The lab draws a vertical column of slots: a dynamic array standing on its end. Index 0 is the
bottom; the top is the last used index, size - 1.
Why the end and not the front? Because of what each costs in an array:
- Adding or removing at the end writes or clears one slot. Nothing moves.
- Adding or removing at the front shifts every other element by one. That is O(n).
So the teaching implementation is a thin wrapper around the language's dynamic array:
push(x): items.append(x)
pop(): if items is empty: fail with underflow
return items.remove_last()
peek(): if items is empty: fail with underflow
return items[last]
Run the Last in, first out preset: 1, 2 and 3 go in, and three pops return 3, 2, 1. The newest element always sits at the highest index.
Costs
| Operation | Time | Why |
|---|---|---|
push |
amortized O(1); O(n) on the push that resizes | Appending to a dynamic array (see the dynamic arrays lesson). |
pop |
O(1) | Removing the last element shifts nothing. |
peek |
O(1) | One read at a known index. |
size, isEmpty |
O(1) | Stored count. |
| space | O(n) | Plus spare capacity left over from growth. |
The O(n) push happens only when the underlying buffer is full. Because buffers grow geometrically, n pushes cost O(n) in total. If you need a strict O(1) bound on every push (rare outside real-time systems), a stack built from linked nodes gives it, at the cost of one allocation and one extra reference per element. Most standard libraries choose the array.
Underflow and overflow
Popping or peeking an empty stack is underflow, and there is no sensible value to return. The teaching implementation checks first and fails loudly. Run the Underflow preset: the first pop is rejected, and the stack keeps working normally afterwards.
| Language | Teaching version | Built-in behaviour on empty |
|---|---|---|
| C# | InvalidOperationException |
Stack<T>.Pop()/Peek() throw InvalidOperationException; TryPop/TryPeek return false |
| Python | IndexError |
list.pop() raises IndexError; items[-1] raises IndexError |
| Java | NoSuchElementException |
ArrayDeque.pop() throws NoSuchElementException, but peek() returns null |
| C++ | std::underflow_error |
std::stack::top() and pop() on an empty stack are undefined behaviour |
Overflow means pushing onto a full stack. A stack on a dynamic array grows instead, so it only
overflows when memory runs out. Fixed-size stacks do overflow: the call stack is one, which is why
unbounded recursion ends in a StackOverflowError (Java), a process crash in .NET, RecursionError
in Python (CPython enforces a depth limit), or undefined behaviour in C++.
Invariants
sizeequals the number of pushes minus the number of successful pops.- The element at index
size - 1is the one pushed most recently among those not yet popped. - The order of the remaining elements, bottom to top, never changes: a stack never reorders.
Using a stack: matching brackets
Is {[()()]} balanced? Is ([)]? Scan left to right. Push every opening bracket. On a closing bracket,
the top of the stack must be its partner; pop it. At the end the stack must be empty.
for ch in text:
if ch in "([{": push(ch)
elif ch in ")]}":
if stack is empty or pop() != partner(ch): return false
return stack is empty
The stack works because brackets nest: the most recently opened one must close first, which is LIFO. The scan is O(n) time and O(n) space in the worst case (all openers). Three failure modes: a closer with an empty stack, a closer that does not match the top, and openers left over at the end.
Using a stack: postfix evaluation
In postfix notation (reverse Polish), the operator follows its operands: 3 4 + 2 * means (3 + 4) * 2.
Push numbers; on an operator, pop two values, apply it, push the result.
3 → [3]
4 → [3, 4]
+ → pop 4, pop 3, push 7 → [7]
2 → [7, 2]
* → pop 2, pop 7, push 14 → [14]
The first value popped is the right operand. For - and / that order matters: 8 2 - is 6, not -6.
Built-in stacks
| C# | Python | Java | C++ | |
|---|---|---|---|---|
| Type | Stack<T> |
list |
ArrayDeque<E> via Deque |
std::stack<T> (adaptor) |
| Push | Push(x) |
append(x) |
push(x) |
push(x) / emplace(...) |
| Pop | Pop() returns the top |
pop() returns the top |
pop() returns the top |
pop() returns void |
| Peek | Peek() |
items[-1] |
peek() |
top() |
| Iteration order | top to bottom | bottom to top | top to bottom | not iterable |
Details that matter:
- C#
Stack<T>is array-backed.Pushis O(1) unless the array must grow, then O(n), as its docs state. Enumerating it, or callingToArray(), yields the top element first. - Python has no stack class; the tutorial recommends a
listwithappendandpop(). Do not usepop(0)orinsert(0, x): those work at the front and are O(n).collections.dequealso works as a stack, andqueue.LifoQueueexists for passing items between threads. - Java has a
Stackclass, but it is a legacy type that extendsVector, so its methods are synchronized and it exposes index-basedVectormethods that break the stack abstraction. Its own Javadoc recommends theDequeinterface instead:Deque<Integer> stack = new ArrayDeque<>();.ArrayDequerejectsnullelements, andpeek()returnsnullon an empty deque rather than throwing, so checkisEmpty()when the difference matters. - C++
std::stackis an adaptor over another container,std::dequeby default;std::vectorandstd::listalso work (std::stack<int, std::vector<int>>).pop()returns nothing: readtop()first, thenpop(). The split exists so that removing an element never depends on copying it out, which could throw and lose the element. The teaching C++ version moves the top out beforepop_back()to return it in one call.
The teaching implementation
The four listings wrap List<T>, list, ArrayList and std::vector, each pushing and popping at the
end, with an explicit empty check before pop and peek. They are checked against one shared fixture
of push, pop and peek sequences, including underflow on an empty stack. In real code, use the built-in
type from the table above; the wrapper exists to show that a stack is a discipline on top of a dynamic
array, not a new kind of memory.
Common mistakes
- Using the front of an array as the top. Each push and pop becomes O(n).
- Popping without checking for empty, or, in C++, calling
top()on an emptystd::stack. - Treating Java's
peek()result as non-null on anArrayDequethat might be empty. - Swapping operands when evaluating postfix: the first pop is the right-hand side.
- Expecting C#'s
Stack<T>and Java's legacyStackto iterate in the same order. The C# stack andArrayDequego top first; Java'sStack, being aVector, goes bottom first.
Edge cases
- Empty stack:
popandpeekunderflow; a laterpushworks normally. - One element: it is both the top and the bottom; one pop empties the stack.
- Push after pop: the freed slot is reused, so the array does not grow again until it is full.
- Many pushes: an occasional push triggers a resize of the underlying array.
Worked practice
1. Starting empty: push 4, push 7, pop, push 1, peek, pop, pop. What do the pop and peek calls return?
Answer
pop → 7, peek → 1, pop → 1, pop → 4. The stack ends empty.
2. Trace the bracket checker on ([)]. Where does it fail?
Answer
Push (, push [. The next character is ), but the top is [, which does not match, so it returns
false at index 2. Counting brackets alone would wrongly accept this string; the stack checks nesting.
3. Evaluate the postfix expression 5 1 2 + 4 * + 3 -.
Answer
1 2 + → 3; 3 4 * → 12; 5 12 + → 17; 17 3 - → 14.
4. For each element of [2, 1, 5, 3], find the next element to its right that is larger (or -1). How can a stack do it in one pass?
Answer
Answer: [5, 5, -1, -1]. Scan left to right keeping a stack of indices still waiting for an answer.
For each new value, pop every waiting index whose value is smaller and record the new value as its
answer, then push the new index. The stack's values always decrease from bottom to top, which is why
it is called a monotonic stack. Each index is pushed and popped at most once: O(n).
Summary
- A stack is LIFO: push, pop and peek, all at the top.
- On a dynamic array the top is the end, so push is amortized O(1) and pop and peek are O(1).
- Underflow must be handled; each language reports it differently, and C++'s
std::stackdoes not check. - Nested structure (brackets, calls, postfix expressions) is where stacks shine.
- Use
Stack<T>, a Pythonlist,ArrayDequethroughDeque, orstd::stack; avoid Java's legacyStack.