Secret Mystery ADT
Week 10, Wednesday
March 11, 2026
Announcements
- PEX4 available (trees)
- PA3 available (genomic intervals), due Week 12
Secret Mystery ADT
First: what types of data can you put into it?
The Mystery Bag
ADT: Priority Queue
insert(key) – add an element
remove_min() – remove and return the smallest element
size() – how many elements?
Where would you use this?
- Emergency room triage (most urgent patient first)
- Task scheduling (highest priority job first)
- Top-k trending from 500M tweets (don’t sort them all!)
- Dijkstra’s shortest path algorithm (coming soon!)
Priority Queue: Implementations
An Aside: A New Kind of Tree
Tell me everything you can about this structure.
(Min-)Heap
Structure property: A complete binary tree – a perfect binary tree, but allowing nodes to be missing from the right side of the bottom level
Heap-order property: Every node’s key \(\leq\) its children’s keys
Recursive definition: A min-heap is either empty, or a node whose key is \(\leq\) the keys of its children, where both subtrees are also min-heaps.
A heap is not a BST!
- BST: left < parent < right (horizontal ordering)
- Heap: parent \(\leq\) children (vertical ordering only)
How would you implement this?
(Min-)Heap Implementation
Navigating the Array
For a node at index i:
- Parent:
- Left child:
- Right child:
(Min-)Heap insert
Heap: insert Implementation
def insert(self, key):
self.size += 1
self.items[self.size] = key
self._heapify_up(self.size)
def _heapify_up(self, i):
if i > _____:
p = parent(i)
if self.items[i] ___ self.items[p]:
self.items[i], self.items[p] = self.items[p], self.items[i]
self._heapify_up(_____)
Running time of insert?
(Min-)Heap removeMin
Heap: removeMin Implementation
def remove_min(self):
min_val = self.items[1]
self.items[1] = self.items[self.size]
self.size -= 1
self._heapify_down(1)
return min_val
def _heapify_down(self, i):
if has_child(i):
mc = min_child(i)
if self.items[i] ___ self.items[mc]:
self.items[i], self.items[mc] = self.items[mc], self.items[i]
self._heapify_down(_____)
Running time of removeMin?
Summary
| Unsorted array |
O(1) |
O(n) |
| Sorted array |
O(n) |
O(1) |
| Heap |
O(log n) |
O(log n) |
Heap Explorer
Summary
- Priority Queue ADT: insert + remove_min
- Heap: a complete binary tree with the heap-order property
- Stored as an array (no pointers needed!)
insert: add at end, bubble up – O(log n)
remove_min: replace root with last, bubble down – O(log n)
Next time: How to build a heap from scratch (faster than you think!)