Stacks
Stacks
A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. Think of a stack of plates — you can only add or remove plates from the top. The last plate placed on top is the first one you take off. This simple constraint makes stacks surprisingly powerful for solving many programming problems.
Core Operations
| Operation | Description | Time Complexity |
|---|---|---|
push(item) | Add an element to the top | O(1) |
pop() | Remove and return the top element | O(1) |
peek() / top() | View the top element without removing it | O(1) |
is_empty() | Check if the stack is empty | O(1) |
size() | Return the number of elements | O(1) |
All operations run in constant time because they only interact with the top of the stack.
How It Works
- Push: Place a new element on top of the stack. Increment the top pointer.
- Pop: Remove the element at the top. Decrement the top pointer. Return the removed element.
- Peek: Read the element at the top without modifying the stack.
The stack maintains a single pointer (or index) tracking the current top position. No searching, shifting, or reordering is ever needed.
Step-by-Step Example
Starting with an empty stack:
push(10) → Stack: [10] (top = 10)
push(20) → Stack: [10, 20] (top = 20)
push(30) → Stack: [10, 20, 30] (top = 30)
pop() → Returns 30, Stack: [10, 20] (top = 20)
peek() → Returns 20, Stack: [10, 20] (unchanged)
pop() → Returns 20, Stack: [10] (top = 10)
Code Snippet
class Stack:
"""Stack implementation using a Python list."""
def __init__(self):
self._items = []
def push(self, item) -> None:
"""Add an element to the top of the stack."""
self._items.append(item)
def pop(self):
"""Remove and return the top element. Raises error if empty."""
if self.is_empty():
raise IndexError("Pop from empty stack")
return self._items.pop()
def peek(self):
"""Return the top element without removing it."""
if self.is_empty():
raise IndexError("Peek at empty stack")
return self._items[-1]
def is_empty(self) -> bool:
"""Check if the stack has no elements."""
return len(self._items) == 0
def size(self) -> int:
"""Return the number of elements in the stack."""
return len(self._items)
Classic Problem: Balanced Parentheses
One of the most common stack applications is checking whether brackets are balanced:
def is_balanced(expression: str) -> bool:
"""Check if parentheses, brackets, and braces are balanced."""
stack = []
opening = "({["
closing = ")}]"
pairs = {")": "(", "}": "{", "]": "["}
for char in expression:
if char in opening:
stack.append(char)
elif char in closing:
if not stack or stack[-1] != pairs[char]:
return False
stack.pop()
return len(stack) == 0
Complexity Analysis
Time Complexity: O(1) per operation
Every stack operation (push, pop, peek) takes constant time. There's no traversal — you always work with the top element directly.
Space Complexity: O(n)
The stack uses space proportional to the number of elements stored. If you push n items, you need O(n) space.
When to Use Stacks
- Function call management: Every programming language uses a call stack to track function invocations, local variables, and return addresses.
- Undo/Redo operations: Text editors push each action onto a stack. Undo pops the last action; redo uses a second stack.
- Expression evaluation: Compilers and calculators use stacks to evaluate arithmetic expressions and convert between infix, prefix, and postfix notation.
- Backtracking algorithms: DFS, maze solving, and puzzle solvers use stacks (explicitly or via recursion) to track the path and backtrack when stuck.
- Browser history: The back button uses a stack of previously visited pages.
- Syntax parsing: Compilers use stacks to match brackets, validate HTML tags, and parse nested structures.
Stack vs. Queue
| Property | Stack (LIFO) | Queue (FIFO) |
|---|---|---|
| Order | Last in, first out | First in, first out |
| Add | Push to top | Enqueue to back |
| Remove | Pop from top | Dequeue from front |
| Use case | Undo, DFS, parsing | BFS, scheduling, buffering |
Array vs. Linked List Implementation
- Array-based (shown above): Simple, cache-friendly, amortized O(1) push. May need resizing.
- Linked list-based: O(1) push/pop without resizing, but uses extra memory for node pointers and has worse cache performance.
For most applications, the array-based implementation is preferred.
Key Properties
| Property | Value |
|---|---|
| Access pattern | LIFO (Last-In, First-Out) |
| Push/Pop | O(1) |
| Random access | Not supported |
| Thread-safe | No (requires synchronization) |