Data Structures · Visualization
Priority Queue: Extract Max
Priority Queue
Extracting the highest-priority item removes and returns the root of the underlying heap, then repairs the heap so the next-highest priority item rises to the top. Time: O(log n). Space: O(1) extra.
Big-O: Insert/serve O(log n).
Priority Queue: Extract Max
Priority QueueExtracting the highest-priority item removes and returns the root of the underlying heap, then repairs the heap so the next-highest priority item rises to the top. This is identical to a heap's extract-max (or extract-min for lowest-priority-first queues).
How Extract Max Works
- Save the root item — this is the current highest priority, to be returned.
- Move the last item in the heap array to the root position.
- Remove the now-duplicate last slot.
- Sift the new root down, swapping with the higher-priority child, until the heap rule holds again.
Extract Max Worked Example
Input: Extract from priority queue heap [D(7), C(5), B(1), A(3)]
- Save max = D(7)
- Move last item A(3) to the root: [A(3), C(5), B(1)]
- Compare A(3) with children C(5), B(1): C(5) is bigger, swap → [C(5), A(3), B(1)]
Output: Served: D (priority 7); remaining heap: [C(5), 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.
Extract Max Time & Space Complexity
When to Use Extract Max
- Running the next-highest-priority process on a CPU scheduler
- Picking the next node to visit in Dijkstra's/Prim's algorithms
- Serving the most urgent patient in a triage system
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.