pq.add(element) # enqueue with a prioritytop = pq.get_max() # serve the most important; raises if empty
💡 Common Mistake:Only the extreme is touched ➔ a priority queue needs no full ordering; a heap’s partial order gives O(logn) both ways, which a fully-sorted list (O(n) insert) can’t match.
When It Flips: linear structures trade add vs get_max; only non-linear structures (heap, balanced tree) make both fast. Applications: Dijkstra/Prim, event-driven simulation, Huffman coding, OS scheduling, A* search.
📊 Exam Execution Trace
Applied Exercise
Problem: Show why a sorted list can’t replace a heap.
Derivation Proof / Hand-Calculation Walkthrough:
sorted list:heap:get_max=O(1),add=O(n)(find slot+shift)get_max=add=O(logn)(partial order suffices)
Final Extracted Output: the heap balances both ops at O(logn); the sorted list is stuck with one O(n) operation.
🧠 Active Recall
Dijkstra does V inserts, V extract-mins, E decrease-keys — compare a binary vs Fibonacci heap and when the difference matters.
Hint: decrease-key cost dominates on dense graphs.
Answer
Short answer: Binary: all O(logV) ⟹ O((V+E)logV); Fibonacci: decrease-key O(1) amort. ⟹ O(E+VlogV) (optimal).
Why:Dense wins ➔ Fibonacci helps when E≫V; on sparse graphs the binary heap’s smaller constants usually win in practice.
Why can't a priority queue just be a kept-sorted list?
Hint: Full order is overkill.
Answer
Short answer: Sorted list gives O(1)get_max but O(n)add (find slot + shift).
Why:Partial order suffices ➔ only the extreme is touched, so a heap’s parent≥child order achieves O(logn) for both.
A heap gives get_max in O(logn) but no efficient search(x) — why, and what if you need both?
Hint: Partial order locates only the extreme.
Answer
Short answer: Parent≥child says nothing about where arbitrary x sits ⟹ search is O(n).
Why:Use a BST ➔ a balanced BST (ordered map) gives O(logn) for min/max, search, insert, and delete alike.