Data Structures · Visualization
Stack: Peek
Stack
Peeking (sometimes called 'top') reads the value on top of the stack without removing it. Time: O(1). Space: O(1).
Big-O: push / pop / peek are all O(1).
Stack: Peek
StackPeeking (sometimes called 'top') reads the value on top of the stack without removing it. On the visualizer's default stack [1, 2, 3] it returns 3 and leaves all three elements in place, which is what separates it from pop(): peek is the pure read you use to decide whether popping is safe. Because it touches one slot, peek is O(1) and allocates nothing; like pop, it must guard against an empty stack, where there is no top to report.
How Peek Works
- Check that the stack is not empty — an empty stack has no top value.
- Read the value at index length - 1, which is 3 in the default stack.
- Return that value to the caller without changing the length or the top pointer.
- Compare with pop(): the same slot is read, but the element survives.
Peek Worked Example
Input: peek() on the default stack [1, 2, 3]
- Highlight index 2 — the top of the default stack.
- Return 3. The stack is still [1, 2, 3], so a following pop() still removes 3.
Output: 3 (the stack remains [1, 2, 3])
Press ▶ Run to watch it step by step.
stack = [1, 2, 3]
top = stack[-1] # peek: look, don't remove
print(top) # 20, stack unchanged
# example: peek on [1, 2, 3]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Peek Time & Space Complexity
When to Use Peek
- Checking the next bracket to match without consuming it yet
- Inspecting the most recent undo action before applying it
- Deciding whether to pop based on the top value, e.g. in expression parsing
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.