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 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. This is identical to a heap's extract-max (or extract-min for lowest-priority-first queues).

How Extract Max Works

  1. Save the root item — this is the current highest priority, to be returned.
  2. Move the last item in the heap array to the root position.
  3. Remove the now-duplicate last slot.
  4. 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)]

  1. Save max = D(7)
  2. Move last item A(3) to the root: [A(3), C(5), B(1)]
  3. 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)]

Introduction
A complete binary tree stored in an array, where every parent is bigger than its children — so the largest value always sits at the root.
90
0
60
1
70
2
20
3
40
4
55
5
66
6
10
7
Bubbling / sifting
Max-Heap — Introduction
Press ▶ Run to watch it step by step.
Python · Heaps in Code
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 queue
Input: Extract from priority queue heap [D(7), C(5), B(1), A(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.

Extract Max Time & Space Complexity

TimeO(log n)
SpaceO(1) extra

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

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.