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

Stack

Peeking (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

  1. Check that the stack is not empty — an empty stack has no top value.
  2. Read the value at index length - 1, which is 3 in the default stack.
  3. Return that value to the caller without changing the length or the top pointer.
  4. Compare with pop(): the same slot is read, but the element survives.

Peek Worked Example

Input: peek() on the default stack [1, 2, 3]

  1. Highlight index 2 — the top of the default stack.
  2. Return 3. The stack is still [1, 2, 3], so a following pop() still removes 3.

Output: 3 (the stack remains [1, 2, 3])

Try your own input
Stack: PeekO(1)
Looks at the top value without removing it.
bottom
1
2
3
← top
Active / highlighted Min stack Result
Stack: Peek
Press ▶ Run to watch it step by step.
Python · Stacks & Queues in Code
stack = [1, 2, 3]
top = stack[-1]  # peek: look, don't remove
print(top)       # 20, stack unchanged
# example: peek on [1, 2, 3]
Input: peek() on the default stack [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

TimeO(1)
SpaceO(1)

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.