Stacks
Last in, first out: the structure behind bracket matching, expression evaluation and the monotonic stack for next greater and next smaller problems.
Overview
A stack keeps items in a pile. You add to the top (push), you look at the top (peek), and you take from the top (pop). The last item you pushed is the first one you get back, so a stack is called LIFO: last in, first out. All three operations cost O(1).
A stack is the right tool whenever the most recent unfinished thing is the one you must deal with next. An opening bracket waits for its closing bracket. A function call waits for the calls it made to return. A day waits for a warmer day.
Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.
What a stack is
The rule: you rarely need to build a stack yourself, because every common language already has one. Only the names change.
- Python: a plain list. Push with s.append(x), pop with s.pop(), peek with s[-1], and test for empty with not s.
- Java: an ArrayDeque. Push with s.push(x), pop with s.pop(), peek with s.peek(), and test for empty with s.isEmpty().
- JavaScript: a plain array. Push with s.push(x), pop with s.pop(), peek with s[s.length - 1], and test for empty with s.length === 0.
Pop, peek and the empty test cost O(1) every time. Push costs O(1) amortized, which means 'on average over many pushes': once in a while the array underneath is full and has to grow, but that rare cost spreads out to a constant per push.
> [!WARNING] > Popping an empty stack is the classic bug. Python raises IndexError, Java's pop() throws NoSuchElementException while peek() returns null, and JavaScript returns undefined without complaint. Check for empty first.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio