Data Structures · Visualization
Queue: Peek
Queue
Peeking reads the item at the front of the queue without removing it. Time: O(1). Space: O(1).
Big-O: enqueue / dequeue are both O(1).
Queue: Peek
QueuePeeking reads the item at the front of the queue without removing it. On the visualizer's default queue [A, B, C] it returns A and leaves the queue intact, which makes it the right tool for deciding whether to dequeue at all — for example, a scheduler that only serves jobs whose priority is high enough. The cost is O(1) because only the front slot is read, and unlike dequeue it never changes the length, so there is no capacity to reclaim; the empty queue still needs guarding because there is no front value to report.
How Peek Works
- Check that the queue is not empty — an empty queue has no front value.
- Read the value at the front index, A in the default queue.
- Return that value to the caller without advancing the front pointer.
- Contrast with dequeue: the same slot is read, but the item stays in the queue.
Peek Worked Example
Input: peek() on the default queue [A, B, C]
- Highlight the front slot — A in the default queue.
- Return A. The queue is still [A, B, C], so a following dequeue() still removes A.
Output: A (the queue remains [A, B, C])
Press ▶ Run to watch it step by step.
from collections import deque
q = deque([1, 2])
front = q[0] # peek: look, don't remove
print(front) # 1, q unchanged
# example: qpeek on [3, 5]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 which customer is next without serving them yet
- Inspecting the next scheduled task before running it
- Deciding whether to process the next item based on its value
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.