Data Structures · Visualization
Priority Queue: Peek
Priority Queue
Peeking looks at the current highest-priority item (the root of the underlying heap) without removing it. Time: O(1). Space: O(1).
Big-O: Insert/serve O(log n).
Priority Queue: Peek
Priority QueuePeeking looks at the current highest-priority item (the root of the underlying heap) without removing it. Because it's always sitting right at the root, this check is instant and doesn't disturb the queue.
How Peek Works
- Check that the priority queue is not empty.
- Read the value at the root of the underlying heap.
- Return it without changing the structure.
Peek Worked Example
Input: Peek at priority queue heap [D(7), C(5), B(1), A(3)]
- Look at the root without removing it: D(7)
Output: D(7) (queue unchanged)
Press ▶ Run to watch it step by step.
import heapq
# heapq is a MIN-heap by default
tasks = []
heapq.heappush(tasks, (3, "low"))
heapq.heappush(tasks, (1, "urgent"))
heapq.heappush(tasks, (2, "normal"))
while tasks:
priority, name = heapq.heappop(tasks)
print(priority, name) # highest priority first
# For max-priority: push (-p, item)
# example: priority queueBehind 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 task would run next without actually starting it
- Deciding whether the next item is worth processing before extracting it
- Displaying 'next up' information in a scheduling dashboard
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.