What Is a Stack?#

A stack is a Last-In, First-Out (LIFO) data structure. The last element you push in is the first one you get out — like a stack of plates: you always take from the top.

Stack123← topPushPopOperationsPush 1 → [1]Push 2 → [1, 2]Push 3 → [1, 2, 3]Pop → returns 3 stack: [1, 2]Peek → returns 2 unchangedLIFO — Last In, First Out

Core Operations#

OperationDescriptionTime
push(item)Add item to the topO(1)
pop()Remove and return topO(1)
peek()View top without removingO(1)
is_empty()Check if stack has itemsO(1)

All core operations are O(1) — that's what makes stacks powerful.


Implementation#

Loading editor…

Interactive Lab#

Watch items get pushed onto and popped off the stack in real time.


The Call Stack#

Your programming language uses a stack under the hood for function calls. Every function call pushes a frame; every return pops it. Recursive functions push many frames — too many causes a "stack overflow".

Call Stack — factorial(3)factorial(1)return 1← pop firstfactorial(2)return 1×1 = 1← popfactorial(3)return 2×1 = 2← popmainresult = 3×2 = 6← pop lastpush →Each call pushes a frame; each return pops it

Classic Problem: Balanced Brackets#

Stacks are perfect for checking whether brackets are matched. The code above includes a full solution — the key insight: push every opening bracket; when you see a closing bracket, pop and verify it matches.

text
Loading editor…

Key Applications#

  • Function call stack (all languages, always running)
  • Balanced parentheses / bracket matching
  • Undo operations in editors (each action is a push)
  • Browser back button (page history)
  • Depth-First Search (iterative version uses a stack)
  • Expression evaluation — converting infix to postfix (shunting-yard)

Key Takeaway#

Stacks are beautifully simple — four operations, all O(1). Whenever you see a problem involving "most recent", "last seen", or "reverse order", a stack is likely the right tool. They're the backbone of recursion, parsing, and state management.