Stack & Queue · Beginner
Stack: Push, Pop, Peek Time O(1) per op Space O(n)
Standard · 🧒 Explain like I'm 10
A stack is a Last-In First-Out (LIFO) data structure with three core operations: push (add to top), pop (remove from top), and peek (read top without removing). All three run in O(1). Stacks appear everywhere: function call frames, undo history, expression parsing, DFS traversal, and balanced bracket checking.
Example: Watch push, pop, and peek operations on a live stack.
When to use this → Balanced brackets / parentheses validation (LC 20) → Undo / redo in text editors and applications → Browser back/forward navigation history → DFS (Depth-First Search) — explicit stack replaces recursion → Evaluate expressions and convert infix to postfix notation → Monotonic stack — next greater element, largest rectangle in histogram Standard 🧒 Explain like I'm 10
← Prev ▶ Play Next → 0.5× 1× 2× 3×
Share step 1 / 12 A stack is a Last-In First-Out (LIFO) structure. Elements are always added and removed from the same end — the top. Think of it as a stack of plates.
Space play/pause← → stepR replay+ − speed
Python JavaScript active line highlighted Copy
1 class Stack : 2 def __init__ ( self ): 3 self . data = [] 4 def push ( self , val ): 5 self . data . append ( val ) 6 def is_empty ( self ): 7 return len ( self . data ) == 0 8 def pop ( self ): 9 return self . data . pop () 10 def peek ( self ): 11 return self . data [- 1 ] 12 def size ( self ): 13 return len ( self . data )
Quick check Which order does a stack process elements?
First-In First-Out (FIFO) Last-In First-Out (LIFO) Random order Sorted order
You push 1, 2, 3 onto a stack. What does three consecutive pops return?
1, 2, 3 3, 2, 1 2, 1, 3 1, 3, 2