Sub topic 14
Decrease-key and indexed heaps
This chapter assumes you know the array layout of a binary heap, sift up and sift down, heapq, and how Dijkstra's algorithm uses a priority queue.
The missing operation
A plain heap can push and pop. Some algorithms also need to lower the priority of an item that is already inside the heap. In Dijkstra's algorithm, for example, you find a shorter path to a node that is already queued. This operation is called decrease-key.
The obstacle is finding the item. A heap is only partially ordered, so searching for a value costs O(n). heapq has no way to locate an item either. Its common workaround is lazy deletion: push a duplicate entry and skip the stale one later. That works, but the heap can grow to the number of edges instead of the number of nodes.
Indexed heaps
An indexed heap stores a second structure, a dictionary mapping each key to its current array position. Every swap updates the dictionary. Finding an item then takes O(1). Decrease-key changes the priority and sifts the item up, which takes O(log n).
An implementation
class IndexedMinHeap:
def __init__(self):
self._items = [] # (priority, key) pairs in heap order
self._pos = {} # key -> index in self._items
def __len__(self):
return len(self._items)
def _swap(self, i, j):
a = self._items
a[i], a[j] = a[j], a[i]
self._pos[a[i][1]] = i
self._pos[a[j][1]] = j
def _up(self, i):
a = self._items
while i > 0:
p = (i - 1) // 2
if a[p][0] <= a[i][0]:
break
self._swap(p, i)
i = p
def _down(self, i):
a, n = self._items, len(self._items)
while True:
c = 2 * i + 1
if c >= n:
break
if c + 1 < n and a[c + 1][0] < a[c][0]:
c += 1
if a[i][0] <= a[c][0]:
break
self._swap(i, c)
i = c
def push(self, key, priority):
if key in self._pos:
raise KeyError(f"{key!r} already in heap")
self._items.append((priority, key))
self._pos[key] = len(self._items) - 1
self._up(len(self._items) - 1)
def decrease_key(self, key, priority):
i = self._pos[key]
if priority > self._items[i][0]:
raise ValueError("new priority is larger")
self._items[i] = (priority, key)
self._up(i)
def pop(self):
a = self._items
if not a:
raise IndexError("pop from empty heap")
top = a[0]
self._swap(0, len(a) - 1)
a.pop()
del self._pos[top[1]]
if a:
self._down(0)
return top[1], top[0]
h = IndexedMinHeap()
h.push("a", 5)
h.push("b", 3)
h.push("c", 8)
h.decrease_key("c", 1)
print(h.pop()) # ('c', 1)
print(h.pop()) # ('b', 3)Every key must be unique, and pop must delete the key from the dictionary. If a swap forgets to update _pos, later lookups point at the wrong slot, and the heap silently breaks.
Trade-offs
| Approach | Heap size | Decrease-key | Extra cost |
|---|---|---|---|
| Lazy deletion with `heapq` | Up to number of pushes | Push a duplicate | Stale pops |
| Indexed heap | Number of live keys | O(log n) | Dictionary and swap bookkeeping |
Both give O(E log V) for Dijkstra, because log E is at most 2 log V. The indexed heap saves memory on dense graphs. In pure Python, lazy deletion is often as fast or faster, since heapq runs in C and your own sifting does not. Choose an indexed heap when memory matters, when you also need to remove or inspect arbitrary keys, or when you use a language without a good built-in heap.
Fibonacci heaps offer O(1) amortized decrease-key. Their constant factors are large, so they rarely beat a binary heap in practice.
Exercise
Add a remove(key) method to IndexedMinHeap. What steps does it need?
Show answer
Look up the index i from the position map. Swap the item at i with the last item, pop the last item, and delete the key from the map. If i is still inside the array, the moved item may violate the heap property in either direction, so call up(i) and down(i). Only one of them will move it. The cost is O(log n).