Binary Heaps and Priority Queues
The Binary Heap
- The binary heap was introduced by Williams (1964) as the basis of heapsort
- A binary heap is another type of binary tree that satisfies two rules:
- A heap condition: determines the order of the tree
- The max-heap variant: the value of each node is greater than or equal to the values of all its descendants
- The min-heap variant: the value of each node is less than or equal to its descendants
- A min-heap is useful when the highest priority means the smallest number
- Completeness: the tree is needs to be filled from left to right on every level
Properties
- The root node always holds the maximum or minimum value
- Searching within a heap is not efficient because you have to inspect each node
- The highest-priority item is always at the top (in a max-heap)
Priority Queue
A priority queue is an abstract data type with two operations that can be built using a binary heap:
- Insert: add an item with an associated priority.
- Delete/Pop: remove and return the item with the highest priority.
Unlike a regular queue, the item that comes out next is not the one that went in first, but the one with the greatest priority value.
Examples
- Patients coming to an A&E are treated in order of severity
- Printers can move jobs based on low and high priority ones
- Load balancers can serve requests based on current load or priority
One straightforward approach is to use a sorted list:
- Keep the list sorted by priority
- The end of the list is the "front" of the queue (the highest-priority item)
- Deletion from the end of an list is \(O(1)\)
To insert a new item we must find its correct position and shift elements to make room which is \(O(N)\).
The Heap Condition
- In a max-heap no node is ever smaller than any of its descendants.
- Other than value order, all other properties of a min-heap are exactly the same as a max-heap
In a BST, left children are smaller and right children are larger. In a heap, both children are simply smaller than their parent. A heap is not sorted, and siblings have no ordering.
Invalid Heap
92 is greater than its parent 88. Which violates the heap condition.
Completeness
- A complete binary tree is filled level by level, left to right
- Completeness guarantees that the tree stays balanced
- A balanced binary tree with \(N\) nodes has approximately \(log^2(N)\) levels
- If we let the tree become lopsided, it could degenerate into a chain of \(N\) nodes an opeartions become \(O(N)\)
Complete Binary Tree
Every level is full except the last, and the last level has no gaps before its rightmost node.
Incomplete Binary Tree
There is a missing node (right child of 88) with nodes still appearing to its right.
The Last Node
- The last node is the rightmost node on the bottom level of the heap
- Both insertion and deletion depends on keeping track of the last node
Heap Insertion Algorithm
To insert a new value into a max-heap:
- Place the new value as the new last node
- Compare the new node with its parent
- If the new node is greater than its parent, swap them
- Repeat step 3, moving upward trickling up until the new node's parent is greater or we reach the root.
Step-by-step
Step 1
If we wanted to insert 40, we would star by inserting it in the position of the last node next to 3
Step 2
Compare 40 with its parent 8, since 40 > 8, we swap them (trickle up)
Step 3
Compare 40 with its new parent 25, since 40 > 25, swap them (trickle up):
Step 4
Since 40 is smaller than 100, we are done.
- This took three comparisons (two swaps), which is proportional to the height of the tree \(O(log N)\)
- The process of moving the node up the heap is known as trickling up
Heap Deletion Algorithm
Only the the root node (the maximum value in a max-heap) is ever deleted.
- Replace the root with the last node (removing the last node from its old position)
- Trickle down the new root to restore the heap condition:
- Compare the trickle node with both of its children
- If the trickle node is smaller than the larger child, swap it with that larger child
- Repeat until the trickle node is not smaller than either child, or it has no children
Step-by-step
We want to delete the root node of 100
Step 1 - Replace Root Node
Replace the root with the last node
Step 2 - Trickle Down
Compare with both children (88 and 25), swap places with the larger of the two children (88) if they are bigger than last node
Repeat Step 2 - Trickle Down
The last node has 87 and 16 as children. Swap places with the larger of the two children 87.
Repeat Step 2 - Trickle Down
The last node has 86 and 50 as children. Swap places with the larger of the two children 86. There are no further children to trickle down.
Array-Based Heaps
- Both insertion and deletion depend on quickly finding the last node
- In a linked tree structure it is difficult to find the last new node after a deletion
- It is more efficient to implement the heap using an array
- The last node is always the last element of array
- The completeness condition ensures that there are no gaps in the resulting array
Navigating the Tree Array
Given that tree can be represented as a list, we use some mathematical properties of the way in which the nodes are organised in the array to calculate the indices of the left, right and parent nodes.
Given a node at index \(i\), the left child is at index:
\[ 2i + 1 \]
The right child is at index:
\[ 2i + 2 \]
The parent is at index:
\[ \left\lfloor \frac{i - 1}{2} \right\rfloor \]
Python Implementation
The methods for navigating the tree array are as follows:
class MaxHeap:
def __init__(self):
self.data = []
def root_node(self):
return self.data[0]
def last_node(self):
return self.data[-1]
def left_child_index(self, index):
return (index * 2) + 1
def right_child_index(self, index):
return (index * 2) + 2
def parent_index(self, index):
return (index - 1) // 2
Python Implementation: Insertion
To add a new value, we place it at the end of the list and trickle up.
def insert(self, value):
# Place the new value at the end (new last node)
self.data.append(value)
# Trickle up the last value appended
self._trickle_up(len(self.data) - 1)
Helper Functions
Trickle Up
Trickles up a value by comparing the new node with its parent and swapping if the new node is larger. Repeats until the node is no longer greater than its parent or it has reached the root (index 0).
def _trickle_up(self, index):
while index > 0:
parent_idx = self.parent_index(index)
if self.data[index] > self.data[parent_idx]:
self.data[index], self.data[parent_idx] = (
self.data[parent_idx], self.data[index]
)
index = parent_idx
else:
break
- The loop breaks if the parent is larger or if the root value is reached
- Worst case the value travels from the bottom to the root, giving \(O(\log N)\) swaps.
- To convert the
MaxHeapclass to aMinHeap, we simply reverse every comparison (change>to<).
Python Implementation: Deletion
def pop(self):
# Guard clause: cannot pop from an empty heap
if len(self.data) == 0:
raise IndexError("Cannot pop from empty heap")
# The root node contains the the maximum value we want to return
value_to_return = self.data[0]
# If there is only one element, just remove it and return
if len(self.data) == 1:
self.data.pop()
return value_to_return
# Step 1: Replace the root with the last node
self.data[0] = self.data.pop()
# Step 2: Trickle down
self._trickle_down(0)
return value_to_return
- There are three cases we handle: empty heap, single element and the general case
self.data.pop()removes the last element and returns ittrickle_idxtracks the displaced node as it moves down.
Helper Functions
Trickle Down
Compare with both children and swap places with the larger of the two children if they are bigger than last node and repeat until there are no children that are larger.
def _trickle_down(self, index):
while self._has_larger_child(index):
larger_idx = self._larger_child_index(index)
# Swap the current node with its larger child
self.data[index], self.data[larger_idx] = (
self.data[larger_idx], self.data[index]
)
# Continue trickling down from the child's position
index = larger_idx
Has Larger Child
The _has_larger_child returns True if at least one child is larger than the node at index.
def _has_larger_child(self, index):
"""Check whether the node at the given index has any child larger than itself."""
left = self.left_child_index(index)
right = self.right_child_index(index)
n = len(self.data)
# Check left child: is it within bounds and larger than the current node?
if left < n and self.data[left] > self.data[index]:
return True
# Check right child: is it within bounds and larger than the current node?
if right < n and self.data[right] > self.data[index]:
return True
return False
Larger Child Index
The _larger_child_index function returns the larger child of a given node.
def _larger_child_index(self, index):
"""Return the index of the larger of the two children of the node at the given index."""
left = self.left_child_index(index)
right = self.right_child_index(index)
if right >= len(self.data):
return left
return right if self.data[right] > self.data[left] else left
Heapifying a List
- Floyd (1964) introduced an algorithm for building an heap from an existing list at \(O(N)\)
- Instead of creating a new heap by inserting each element into the heap one by one, Floyd treats the nodes as an existing heap
- Only perform the trickle down operation from last non-leaf node (last node in the array with at least one child)
- Useful when you already have existing data rather than appending as it arrives
- Has \(O(N)\) efficiency because about half the nodes are leaves which do not need trickling down
def heapify(self, items):
self.data = list(items)
# Start at the last non-leaf node and work back to the root
# Same as finding parent index of last node
last_non_leaf = len(self.data) // 2 - 1
for i in range(last_non_leaf, -1, -1):
self._trickle_down(i)
heapq Module
Python provides a heap implementation in the standard library via the heapq module.
- The heapify method converts a list into a heap
The heapify function converts the list into a heap in-place, moving the elements
import heapq numbers = [10, 15, 65, 23, 69, 11] heapq.heapify(numbers) print(numbers) # [10, 15, 11, 23, 69, 65]We can use heappop to pop items from the list in order
print(heapq.heappop(numbers)) # 10- We can add things to the heap using heappush
- heapq orders directly by value, but when we want to attach extra data, it is common practice to use a tuple
- This pattern of attaching a value to an element is useful for building a priority queue
- Python compares the tuple element-by-element from left to right
tasks = []
heapq.heappush(tasks, (2, "Do this second"))
heapq.heappush(tasks, (1, "Do this first"))
heapq.heappush(tasks, (3, "Do this last"))
# Items come out in order of smallest priority number first
print(heapq.heappop(tasks)) # (1, 'Do this first')
print(heapq.heappop(tasks)) # (2, 'Do this second')
Min and Max heapq
- heapq is a min-heap by default: the smallest item is always at index 0
- Max-heap variants of the heapq functions have a
_maxsuffixheapify_maxturns a list into a max-heapheappush_maxpushes an item onto a max-heapheappop_maxpops and returns the largest item
With a max-heap, the largest item is at index 0
numbers = [10, 15, 65, 23, 69, 11] heapq.heapify_max(numbers) print(numbers) # [69, 23, 65, 10, 15, 11] print(heapq.heappop_max(numbers)) # 69- A list that is a min-heap must only be used with the plain functions, and a max-heap only with the max functions
Finding Top-k
- A typical use case is to find the largest and smallest numbers in a list
- We can build a heap of a restricted size to keep track of the largest or smallest values encountered
- A min-heap is used to track the top-k because the smallest value is the one we want to eliminate on each append
- For bottom-k a max-heap will eliminate the largest values
- Each
addis \(O(log k)\) and there is no need to rescan old data - Note the use of heapreplace to pop smallest item and push new item at same time
import heapq
class TopK:
def __init__(self, k):
self.k = k
self.heap = []
def add(self, x):
if len(self.heap) < self.k:
heapq.heappush(self.heap, x)
elif x > self.heap[0]:
heapq.heapreplace(self.heap, x)
def top(self):
return sorted(self.heap, reverse=True)
Usage:
numbers = [10, 15, 65, 23, 69, 11]
tracker = TopK(3)
for n in numbers:
tracker.add(n)
print(f"added {n} - {tracker.heap}")
print(tracker.top())
added 10 - [10] added 15 - [10, 15] added 65 - [10, 15, 65] added 23 - [15, 23, 65] added 69 - [23, 69, 65] added 11 - [23, 69, 65] [69, 65, 23]
Merging
- If we have multiple pre-sorted lists we can use a heap to perform the merging efficiently
heapq.merge merges the lists element by element using a generator rather than all at once
a = [1, 5, 9] b = [2, 6, 10] c = [3, 4, 8] merged = list(heapq.merge(a, b, c)) print(merged) # [1, 2, 3, 4, 5, 6, 8, 9, 10]- Keep the current front item of each list in a min-heap
- The smallest remaining item overall must be the first item in one of the lists
- Pop the smallest overall item, yield it from the generator
- Push the next item from that same list so that the heap can consider the next overall item
Summary
- An ordered array gives \(O(1)\) deletion but \(O(N)\) insertion, which is a bottleneck
- A priority queue serves items by priority, not by arrival order
- A binary max-heap is a complete binary tree where every node is greater than its descendants
- Heaps are typically implemented using arrays. The last element of the array is the last node, making insertion and deletion straightforward
- Heapify can be used to convert an existing array in to a heap
- Heaps are not suitable for search, but useful when you only need the maximum (or minimum) value
References
Exercises
Given the list below, use heapq to turn it into a heap in-place, then print the result.
numbers = [15, 3, 22, 7, 1, 9, 14]
- What is the value at index 0?
- Push the values 0 and 11 to
numbers - Pop three times from
numbersand print each popped value. - Print the two largest and smallest numbers
A&E Triage
Build an A&E triage class using a max heap from heapq
- Patients are seen in order of severity (5 = most urgent, 1 = least urgent).
- Use a tuple
(severity, name)as the elements in the list. Push these patients, then pop until empty. Try out this code to see the order in which patients come out, why do some patients with the same priority come ahead of others?
import heapq queue = [] heapq.heappush_max(queue, (3, "Beau")) heapq.heappush_max(queue, (5, "Elise")) heapq.heappush_max(queue, (1, "Arnold")) heapq.heappush_max(queue, (1, "Del")) while queue: print(heapq.heappop_max(queue))- Fix the priority queue so that patients with the same priority are seen in the order that they arrived.
- Hint: since we are using a max-heap we want to use an additional negative number that tracks the order of arrival by counting backwards
- Build a
Triageclass that tracks waiting patients:- Implement an
add()method to add patients to the queue - Add a
next_patient()method to return the next patient to treat and remove them from the queue - Create a
most_urgent(n: int)method which returns a list of the nextnpatients to be treated
- Implement an