Data Structures · Visualization

Stack: Introduction

Stack

A stack is a collection where items are added and removed from only one end, called the 'top'. Time: O(1) for push, pop, and peek. Space: O(n).

Big-O: push / pop / peek are all O(1).

Stack: Introduction

Stack

A stack is a collection where items are added and removed from only one end, called the 'top'. It follows the LIFO rule — Last In, First Out — meaning the most recently added item is always the first one to come out, just like a stack of plates: you place a new plate on top, and you take the top plate off first.

How Stack: Introduction Works

  1. Keep track of the 'top' of the stack (the most recently added item).
  2. To add an item, place it on top (push).
  3. To remove an item, take the one currently on top (pop).
  4. Optionally, peek at the top item without removing it.

Stack: Introduction Worked Example

Input: Push 1, push 2, push 3, then pop

  1. Push 1 → stack: [1]
  2. Push 2 → stack: [1, 2]
  3. Push 3 → stack: [1, 2, 3]
  4. Pop → removes 3 (last in) → stack: [1, 2]

Output: Popped value: 3, remaining stack: [1, 2]

📖 Introduction: this is an overview of the topic, so there's nothing to run here. Pick an operation from the side menu to see a live, step-by-step animation.
Stack: Introduction
A Last-In-First-Out (LIFO) structure — you can only add or remove from the top, like a stack of plates.
bottom
1
2
3
← top
Active / highlighted Min stack Result
Stack: Introduction
Press ▶ Run to watch it step by step.
Python · Stacks & Queues in Code
# Stack (LIFO): push/pop at the same end
stack = [1, 2, 3]
stack.append(1); stack.append(2); stack.pop()

# Queue (FIFO): enqueue one end, dequeue the other
from collections import deque
q = deque()
q.append(1); q.append(2); q.popleft()
# example: intro 1 on [1, 2, 3]

Stack: Introduction Time & Space Complexity

TimeO(1) for push, pop, and peek
SpaceO(n)

When to Use Stack: Introduction

  • Undo/redo functionality in editors
  • Tracking function calls (the call stack) during program execution
  • Checking balanced parentheses/brackets in code
  • Browser back-button history

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.