From undo buttons to function calls — stacks are everywhere in computing.
What Is a Stack?
A stack is a linear data structure that follows the LIFO principle:
Last In, First Out — the most recently added element is the first one removed.
Think of a physical stack of plates:
- You always add (push) a plate on top.
- You always remove (pop) from the top.
- You can only look at (peek) the top plate without removing it.
- You cannot access a plate in the middle without removing all the ones above it.
┌─────┐ push → │ D │ ← pop ├─────┤ │ C │ ├─────┤ │ B │ ├─────┤ │ A │ └─────┘ bottom Stack ADT: The Interface
A stack supports these core operations:
| Operation | Description | Complexity |
|---|---|---|
push(x) | Add element x to the top | O(1) |
pop() | Remove and return the top element | O(1) |
peek()/top() | Return top element without removing | O(1) |
isEmpty() | Return True if stack has no elements | O(1) |
size() | Return number of elements | O(1) |
All operations are O(1) — that's what makes stacks so attractive.
Implementation 1: Stack Using an Array
class ArrayStack: def __init__(self, capacity=100): self.arr = [None] * capacity self.top = -1 # -1 means empty self.capacity = capacity def push(self, data): if self.top == self.capacity - 1: raise OverflowError("Stack is full") self.top += 1 self.arr[self.top] = data def pop(self): if self.isEmpty(): raise IndexError("Stack underflow — popping from empty stack") data = self.arr[self.top] self.arr[self.top] = None self.top -= 1 return data def peek(self): if self.isEmpty(): raise IndexError("Stack is empty") return self.arr[self.top] def isEmpty(self): return self.top == -1 def size(self): return self.top + 1 Pros: Simple, O(1) for all ops, cache-friendly.
Cons: Fixed capacity — can overflow.
Implementation 2: Stack Using a Linked List
class Node: def __init__(self, data): self.data = data self.next = None class LinkedStack: def __init__(self): self.top_node = None self._size = 0 def push(self, data): node = Node(data) node.next = self.top_node # New node points to old top self.top_node = node # New node becomes top self._size += 1 def pop(self): if self.isEmpty(): raise IndexError("Stack underflow") data = self.top_node.data self.top_node = self.top_node.next # Move top down self._size -= 1 return data def peek(self): if self.isEmpty(): raise IndexError("Stack is empty") return self.top_node.data def isEmpty(self): return self.top_node is None def size(self): return self._size Pros: Dynamic size — no overflow.
Cons: Extra memory per node (pointer overhead), less cache-friendly.
Python's Built-in Stack
Python lists work perfectly as stacks:
stack = [] stack.append(10) # push stack.append(20) stack.append(30) print(stack[-1]) # peek → 30 stack.pop() # pop → removes 30 stack.pop() # pop → removes 20 print(stack) # → [10] list.append() and list.pop() are both O(1) amortized. Python lists are the idiomatic stack in Python.
Application 1: Balanced Parentheses Checker
Given a string of brackets (), [], {}, check if they're correctly balanced.
def is_balanced(s): stack = [] matching = {')': '(', ']': '[', '}': '{'} for char in s: if char in '([{': stack.append(char) # Push opening bracket elif char in ')]}': if not stack or stack[-1] != matching[char]: return False # Mismatch stack.pop() return len(stack) == 0 # Balanced if stack is empty at end print(is_balanced("({[]})")) # True print(is_balanced("({[})")) # False print(is_balanced("((()")) # False Complexity: O(n) time, O(n) space.
Application 2: Expression Evaluation (Postfix)
Regular (infix) notation: 3 + 4 * 2
Postfix notation: 3 4 2 * +
Postfix is unambiguous (no need for parentheses or operator precedence rules) and easy to evaluate with a stack:
def evaluate_postfix(expression): stack = [] tokens = expression.split() for token in tokens: if token.lstrip('-').isnumeric(): stack.append(int(token)) # Push operand else: b = stack.pop() a = stack.pop() if token == '+': stack.append(a + b) elif token == '-': stack.append(a - b) elif token == '*': stack.append(a * b) elif token == '/': stack.append(int(a / b)) return stack.pop() print(evaluate_postfix("3 4 2 * +")) # 3 + (4*2) = 11 Compilers use this technique internally.
Application 3: Undo / Redo Functionality
Every text editor's undo feature is a stack:
class TextEditor: def __init__(self): self.text = "" self.undo_stack = [] self.redo_stack = [] def type(self, chars): self.undo_stack.append(self.text) # Save current state self.redo_stack.clear() # Clear redo on new action self.text += chars def undo(self): if self.undo_stack: self.redo_stack.append(self.text) self.text = self.undo_stack.pop() def redo(self): if self.redo_stack: self.undo_stack.append(self.text) self.text = self.redo_stack.pop() Application 4: Function Call Stack
This is the most important real-world use of stacks. When your program calls a function, the runtime pushes a stack frame containing:
- Return address
- Local variables
- Function parameters
When the function returns, its frame is popped off the stack.
def factorial(n): if n == 1: return 1 # Base case: start popping return n * factorial(n - 1) # Recursive call: push frame For factorial(4), the call stack looks like:
Push: factorial(4) Push: factorial(3) Push: factorial(2) Push: factorial(1) ← base case reached Pop: factorial(1) → returns 1 Pop: factorial(2) → returns 2*1 = 2 Pop: factorial(3) → returns 3*2 = 6 Pop: factorial(4) → returns 4*6 = 24 A "stack overflow" error literally means the call stack has grown too large.
Application 5: Depth-First Search (DFS)
Stacks are used to implement DFS iteratively:
def dfs(graph, start): visited = set() stack = [start] while stack: node = stack.pop() if node not in visited: visited.add(node) print(node) for neighbor in graph[node]: if neighbor not in visited: stack.append(neighbor) Recursive DFS implicitly uses the call stack; iterative DFS uses an explicit stack.
Monotonic Stack: An Advanced Pattern
A monotonic stack maintains elements in a sorted order. It's useful for finding the next greater/smaller element efficiently.
def next_greater_element(arr): result = [-1] * len(arr) stack = [] # Stores indices for i in range(len(arr)): while stack and arr[stack[-1]] < arr[i]: idx = stack.pop() result[idx] = arr[i] # arr[i] is the next greater for idx stack.append(i) return result print(next_greater_element([2, 1, 2, 4, 3])) # Output: [4, 2, 4, -1, -1] This runs in O(n) — each element is pushed and popped at most once.
Common Stack Interview Problems
- Valid parentheses — Bracket matching.
- Min stack — Stack that supports getMin() in O(1).
- Daily temperatures — Next warmer day for each day.
- Largest rectangle in histogram — Classic monotonic stack problem.
- Decode string — Expand encoded strings like
3[abc]. - Evaluate reverse Polish notation — Postfix evaluation.
- Asteroid collision — Simulate collisions using a stack.
Summary
- A stack follows LIFO — last in, first out.
- All core operations (
push,pop,peek,isEmpty) are O(1). - Can be implemented with an array (fixed size, cache-friendly) or linked list (dynamic size).
- Real-world uses: function call stack, undo/redo, DFS, expression evaluation, bracket matching.
- Monotonic stacks solve next-greater-element problems in O(n).
- In Python, use
list.append()andlist.pop()as a stack — simple and efficient.
This completes our journey through the core data structures in the DSA topic-wise notes. From basic principles to linked lists to stacks — you now have a solid foundation to tackle more advanced topics like queues, trees, heaps, and graphs.
