Stacks
Indexed description
- Coding Interview Patterns
- /
- Stacks
No questions available
A stack is a data structure that follows the Last-In, First-Out (LIFO) principle. The last item you put in is the first item you take out.
Think of a stack of plates. You add plates on top and remove from the top. You can't pull a plate from the middle or bottom without removing everything above it first.
Stacks are everywhere in programming. Every time you call a function, it goes on the call stack. When you hit undo in a text editor, it pops the last action from a stack. Browser back button? Stack.
A stack supports only a few operations, and that's what makes it powerful. You don't need random access. You only care about the top.
- push(item): Add an item on top of the stack
- pop(): Remove and return the top item
- peek() / top(): Look at the top item without removing it
- isEmpty(): Check if the stack has no items
- size(): How many items are in the stack
Notice that every operation is O(1). That's the beauty of a stack. You never search, you never iterate. You only touch the top.
Loading visualization...
In most languages, you don't need to build a stack from scratch. Arrays and built-in collections work perfectly.
- Array-based: Items are stored in contiguous memory. push/pop just move a pointer. Very cache-friendly and fast.
- Linked list-based: Each node points to the one below it. Push adds a new head, pop removes the head. Uses more memory because of the pointers.
Array-based Linked list-based push() O(1) amortized O(1) pop() O(1) O(1) Memory Compact, cache-friendly Extra pointer per node Best for Almost everything When max size is unknown and memory is tight
Stacks Show Up More Than You Think
- Function call stack: Every function call pushes a frame. When it returns, the frame is popped. This is how recursion works under the hood.
- Undo/Redo: Text editors push each action onto a stack. Undo pops the last action. Redo uses a second stack.
- Browser history: Back button pops the current page and pushes it onto a forward stack.
- Expression evaluation: Calculators use stacks to handle operator precedence and parentheses.
- Syntax parsing: Compilers use stacks to match brackets, parse HTML tags, and validate nested structures.
- Matching pairs: Anything that opens and closes (brackets, tags, quotes). Push the opener, pop when you see the closer.
- "Next greater" or "next smaller": A monotonic stack solves this in one pass. Keep the stack sorted, pop elements that violate the order.
- Undo operations: Anything where you need to reverse the most recent action.
- Nested structures: Parsing expressions, handling nested groups, function calls.
- Converting recursion to iteration: Any recursive algorithm can be rewritten with an explicit stack. This is exactly what DFS does.
- Popping from an empty stack. Always check isEmpty() before calling pop() or peek(). Forgetting this causes runtime errors.
- Using Java's Stack class. The java.util.Stack class is legacy and synchronized (slow). Use ArrayDeque instead.
- Forgetting items left in the stack. In monotonic stack problems, items remaining after the loop have no "next greater" element. Don't forget to handle them (usually set to -1).
- Confusing stack with queue. Stack is LIFO (last in, first out). Queue is FIFO (first in, first out). If you need level-order processing, you need a queue, not a stack.
Related concepts
- Introduction to Two Pointers Pattern
- Valid Parentheses
- Remove All Adjacent Duplicates In String
- Min Stack
- Daily Temperatures
Create a free Caio profile to unlock more results and save your role and location preferences.
Unlock free search