Push, pop, and peek
- Push adds an item to the top.
- Pop removes and returns the top item.
- Peek reads the top without removing it.
These operations are O(1) on a typical stack implementation; Python list append and pop at the end are amortized constant time. Searching for a buried item takes O(n), because items above it must be removed or scanned by another method.
Choose Mode in the visualizer. In stack mode, try Push, Pop, and Peek; in bracket mode, compare a valid sequence with a mismatched one. The top is the only item directly accessible.
Worked example: balanced brackets
When scanning ([{}]), push each opening bracket. On a closing bracket, pop and check that it matches the most recent opener. The order matters: the last bracket opened must close first. The sequence is valid only if no mismatch occurs and the stack is empty at the end.
def balanced(text):
matching = {")": "(", "]": "[", "}": "{"}
stack = []
for char in text:
if char in "([{":
stack.append(char)
elif char in matching:
if not stack or stack.pop() != matching[char]:
return False
return not stack
The final check catches leftover open brackets such as (((, which have no mismatch but are still incomplete.
Where stacks appear
Function calls use a call stack to remember arguments, local variables, and where to resume. Recursive algorithms rely on it; extremely deep recursion can exceed a language’s stack limit. An explicit stack is also used by depth-first search, expression evaluation, and undo systems, where the latest unresolved task or action is handled first.
In Python, append and pop at the end of a list are a simple stack. Do not use pop(0) for a stack: removing from the front shifts the remaining list. Use a deque when efficient operations at both ends are required.
Common mistakes with Stacks
- Popping an empty stack: check before removal when the input may be malformed.
- Checking only for mismatches: verify the stack is empty at the end.
- Using a stack for FIFO order: a queue is the right structure when the oldest item should leave first.
- Reaching into the middle: that breaks the simple LIFO interface and costs linear time.