What is the difference between a heap and a priority queue?
A heap is a data structure: a complete binary tree arranged so that every parent is no greater than its children, which makes the smallest element sit at the root. A priority queue is an interface: a collection where you can insert items with a priority and always remove the one with the highest priority.
The priority queue is usually implemented with a heap, but the two words are used loosely and interchangeably in industry. When someone says use a priority queue in an interview, they almost always mean use a heap underneath, because the heap gives you logarithmic insertion and removal of the extreme element.
import heapq
tasks = [(3, "write docs"), (1, "fix bug"), (2, "review pull request")]
heapq.heapify(tasks)
print(tasks[0])The output is the tuple one and fix bug, because heapify arranges the list so the smallest tuple is at index zero, and the tuple comparison orders by the first element, which is the priority.
The mechanism is the heap invariant combined with the complete tree layout. Because the tree is complete, the children of the node at index i are at two i plus one and two i plus two, so the structure can live in a plain array with no pointers. The invariant lets the smallest element be found in constant time and the next smallest be restored in logarithmic time after a removal.
The trade-off to name is that a heap only gives you the extreme element cheaply. Finding the fifth smallest is linear, and removing an arbitrary element is linear too, because the heap has no ordering among the non-root elements. If you need more than the extreme, a balanced tree or a sorted structure is the better tool, and that is the point to make when choosing a data structure in a design discussion.