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
StackA 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
- Keep track of the 'top' of the stack (the most recently added item).
- To add an item, place it on top (push).
- To remove an item, take the one currently on top (pop).
- Optionally, peek at the top item without removing it.
Stack: Introduction Worked Example
Input: Push 1, push 2, push 3, then pop
- Push 1 → stack: [1]
- Push 2 → stack: [1, 2]
- Push 3 → stack: [1, 2, 3]
- Pop → removes 3 (last in) → stack: [1, 2]
Output: Popped value: 3, remaining stack: [1, 2]
Press ▶ Run to watch it step by step.
# 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
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
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.