Skip to main content

DSAPath12 mincore

Heap vs Priority Queue

A priority queue is an abstract interface; a heap is a common implementation that makes insert and extract-min efficient.

DifficultyCore
TierTier 1
ModuleComparisons
LanguagesPython

Why This Matters

Learners often say "heap" when they mean "priority queue." The difference matters because one is the contract and the other is one way to satisfy it.

Decision Rule

Say priority queue when describing the operation you need: insert an item with priority and repeatedly remove the best item. Say heap when describing the array-based tree structure used to implement those operations.

Comparison Table

ConceptPriority queueHeap
Typeabstract data typeconcrete data structure
Core operationget min or max by prioritymaintain heap invariant
Common implementationbinary heap, pairing heap, Fibonacci heapbinary heap in arrays
Python interfaceheapq functions approximate min-priority queue behaviorheapq stores heap in a list
Used byDijkstra, A*, top-k, schedulingthe implementation behind many priority queues

Worked Example

Dijkstra's algorithm needs a priority queue because it asks for the unsettled vertex with smallest current distance. In Python, heapq implements that priority queue with a min-heap list of (distance, vertex) pairs.

The algorithm cares about the priority queue behavior. The code cares about the heap invariant.

Common Mistakes

MistakeCorrection
Calling every priority queue a binary heap.Binary heap is common, not the only implementation.
Expecting Python heapq to support decrease-key directly.Most Python Dijkstra code pushes a new pair and skips stale entries.
Forgetting tuple tie behavior in Python.If priorities tie, Python compares later tuple fields. Add a counter if needed.

Diagnostic Questions

QuestionAnswer signal
Which one is the abstraction?Priority queue.
Which one has parent-child index relationships?Binary heap.
Why does Dijkstra use one?It needs efficient extraction of the smallest tentative distance.

Exercises

  • Beginner: Push (3, "A"), (1, "B"), (2, "C") into a min-heap and list pop order.
  • Beginner: Explain why a sorted list can implement a priority queue but may be slower for insertion.
  • Beginner: Name two algorithms that use priority queues.
  • Intermediate: Implement top-k largest elements using a min-heap of size k.
  • Intermediate: Implement Dijkstra with lazy stale-entry skipping.
  • Challenge: Compare binary heap and Fibonacci heap operation bounds at a high level.

References