Data Structure
Stack
A Last-In, First-Out (LIFO) structure — think of a stack of plates. You can only add or remove from the top, which is exactly what makes every operation O(1): no shifting, just move one pointer.
PushO(1)
PopO(1)
PeekO(1)
OrderLIFO
Try It — Animated Flow
top
5
12
8
Peek returns 8 without removing it — O(1).
Step 1 / 1
Pointer / current
Comparing
Swapping / removing
Newly inserted
Settled
Java Implementation
Real-Life Usage
Undo / Redo history
Every edit is pushed onto a stack. Ctrl+Z pops the most recent action — exactly the LIFO order you want for undo.
Browser back button
Each page you visit is pushed onto a history stack; hitting Back pops the most recently visited page.
Function call stack
Every function call pushes a stack frame; when it returns, that frame is popped — this is literally how recursion works under the hood.
Matching brackets
Validating `{[()]}` pushes opening brackets and pops on each closing one — a mismatch means the stack doesn't end empty.
Trade-offs
Reach for a stack when
- You need to reverse an order or backtrack (undo, DFS)
- Only the most recent item is ever relevant next
- You're matching nested/paired structures
Avoid it when
- You need to access elements in the middle
- Processing needs to happen in arrival order (use a Queue)
- You need fast lookup by value (use a Set/Map)