Data Structures · Visualization
Priority Queue: Introduction
Priority Queue
A priority queue is a collection where each item has a priority, and the item with the highest (or lowest, depending on the setup) priority is always the one served next — regardless of the order items were added. Time: O(log n) to insert or serve the next item, O(1) to peek. Space: O(n).
Big-O: Insert/serve O(log n).
Priority Queue: Introduction
Priority QueueA priority queue is a collection where each item has a priority, and the item with the highest (or lowest, depending on the setup) priority is always the one served next — regardless of the order items were added. It is not a physical structure of its own; it is usually implemented using a heap, because a heap already keeps the most extreme value instantly accessible at the root.
How Priority Queue: Introduction Works
- Assign a priority value to every item that gets added.
- Use a heap (max-heap for 'highest priority first', min-heap for 'lowest priority first') to store the items.
- Insert new items using the heap's insert operation.
- Always serve the next item by extracting the root of the heap.
Priority Queue: Introduction Worked Example
Input: Add tasks with priorities: A(3), B(1), C(5), then serve the next task
- Insert A(3), B(1), C(5) into a max-priority heap
- Heap keeps C(5) at the root since it has the highest priority
- Serve next → extract C(5)
Output: Served: C (priority 5); remaining: A(3), B(1)
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.
Priority Queue: Introduction Time & Space Complexity
When to Use Priority Queue: Introduction
- Operating system task/process scheduling
- Dijkstra's and Prim's algorithms, which always expand the cheapest option next
- Hospital emergency room triage systems
- Event-driven simulations that process events in time order
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.