Sub topic 13
Decrease-Key, Lazy Deletion, and Fibonacci Heaps
This chapter assumes you already know the heap-based Dijkstra from earlier chapters, in which a new entry is pushed on every improvement and stale entries are skipped. It also assumes you know the complexity results for array and binary-heap versions and can read Python classes. The goal is to compare the two ways of handling a distance improvement inside the priority queue, and to see where Fibonacci heaps fit.
The Problem Both Strategies Solve
When Dijkstra relaxes edge (u, v) and finds a shorter tentative distance for v, the priority queue must start treating v as closer. If v is not yet in the queue, you insert it. If v is already in the queue with an older, larger key, there are two options:
- Decrease-key. Find v's existing entry, lower its key, and restore the heap order. The queue holds at most one entry per vertex.
- Lazy deletion. Leave the old entry where it is and push a second entry with the smaller key. The old entry becomes stale: when it is popped later, the algorithm sees that v is already finalized and discards it.
Both strategies produce the same distances. They differ in memory, in how often the heap is touched, and in how much code you have to write.
Why heapq Cannot Decrease a Key
Python's heapq works on a plain list and has no notion of where a given item sits. A decrease-key needs that index, because the entry has to be sifted up from its current position. Searching the list takes O(n) time, which wipes out the benefit of a heap.
Editing an entry in place does not work either:
A real decrease-key needs an indexed heap: a heap plus a dictionary that maps each item to its current array index. Every swap has to update that dictionary.
An Indexed Binary Heap with Decrease-Key
The class below is a complete min-heap that supports push, pop, and decrease_key in O(log n) each. Heap entries are (key, item) tuples, but comparisons look only at keys, so items never need to be comparable.
class IndexedMinHeap:
def __init__(self):
self.heap = [] # list of (key, item)
self.pos = {} # item -> index in self.heap
def __len__(self):
return len(self.heap)
def __contains__(self, item):
return item in self.pos
def push(self, item, key):
self.heap.append((key, item))
self.pos[item] = len(self.heap) - 1
self._sift_up(len(self.heap) - 1)
def decrease_key(self, item, key):
i = self.pos[item]
if key >= self.heap[i][0]:
return # not an improvement
self.heap[i] = (key, item)
self._sift_up(i)
def pop(self):
last = self.heap.pop()
if not self.heap:
del self.pos[last[1]]
return last
top = self.heap[0]
self.heap[0] = last
self.pos[last[1]] = 0
del self.pos[top[1]]
self._sift_down(0)
return top
def _swap(self, i, j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
self.pos[self.heap[i][1]] = i
self.pos[self.heap[j][1]] = j
def _sift_up(self, i):
while i > 0:
parent = (i - 1) // 2
if self.heap[i][0] < self.heap[parent][0]:
self._swap(i, parent)
i = parent
else:
break
def _sift_down(self, i):
n = len(self.heap)
while True:
left, right, smallest = 2 * i + 1, 2 * i + 2, i
if left < n and self.heap[left][0] < self.heap[smallest][0]:
smallest = left
if right < n and self.heap[right][0] < self.heap[smallest][0]:
smallest = right
if smallest == i:
break
self._swap(i, smallest)
i = smallestDijkstra Using Decrease-Key
With the indexed heap, the main loop has no stale-entry check, because every pop returns a live vertex. It does need to tell apart "never seen" (insert), "in the queue" (decrease-key), and "finalized" (ignore).
def dijkstra_decrease_key(graph, source):
dist = {source: 0}
prev = {}
pq = IndexedMinHeap()
pq.push(source, 0)
done = set()
while pq:
d, u = pq.pop()
done.add(u)
for v, w in graph.get(u, []):
if v in done:
continue
nd = d + w
if v not in dist:
dist[v] = nd
prev[v] = u
pq.push(v, nd)
elif nd < dist[v]:
dist[v] = nd
prev[v] = u
pq.decrease_key(v, nd)
return dist, prev
graph = {
"A": [("B", 4), ("C", 1)],
"C": [("B", 2), ("D", 5)],
"B": [("D", 1)],
"D": [],
}
dist, prev = dijkstra_decrease_key(graph, "A")
print(dist) # {'A': 0, 'B': 3, 'C': 1, 'D': 4}
print(prev) # {'B': 'C', 'C': 'A', 'D': 'B'}The elif branch relies on one fact: a vertex that is in dist but not in done must still be in the queue. Breaking that fact, for example by popping without adding to done, makes decrease_key raise a KeyError.
Measuring the Cost of Lazy Deletion
Lazy deletion's weakness is that the heap can hold up to one entry per successful relaxation, which is O(E) entries instead of O(V). The graph below is built so that every finalized vertex improves every later vertex. Node i has an edge to each node j > i with weight (j − i)².
import heapq
def build_graph(n):
return {i: [(j, (j - i) ** 2) for j in range(i + 1, n)] for i in range(n)}
def lazy_counts(graph, source):
dist = {source: 0}
heap = [(0, source)]
visited = set()
pushes, stale = 1, 0
while heap:
d, u = heapq.heappop(heap)
if u in visited:
stale += 1
continue
visited.add(u)
for v, w in graph[u]:
nd = d + w
if v not in dist or nd < dist[v]:
dist[v] = nd
heapq.heappush(heap, (nd, v))
pushes += 1
return pushes, stale
print(lazy_counts(build_graph(100), 0)) # (4951, 4851)When node k is finalized with distance k, it improves every node j > k, because k + (j − k)² is smaller than the previous best (k − 1) + (j − k + 1)². That gives 1 + n(n − 1)/2 = 4951 pushes for n = 100, and all but 100 of them end up stale. The decrease-key version on the same graph never holds more than 100 entries.
That sounds bad for lazy deletion, but the time bound barely moves. Each push and pop costs O(log E), and since E ≤ V², log E ≤ 2 log V. So lazy deletion still runs in O(E log V). The real cost is memory: O(E) for the heap instead of O(V).
Fibonacci Heaps
A Fibonacci heap makes decrease-key cheaper in amortized terms. It keeps a loose collection of heap-ordered trees and does most of its restructuring work during extract-min.
| Operation | Binary heap | Fibonacci heap (amortized) |
|---|---|---|
| insert | O(log V) | O(1) |
| extract-min | O(log V) | O(log V) |
| decrease-key | O(log V) | O(1) |
Dijkstra does V extract-mins and up to E decrease-keys, so the totals are:
| Implementation | Time | Queue memory |
|---|---|---|
| Unsorted array | O(V²) | O(V) |
| Binary heap, decrease-key | O(E log V) | O(V) |
| Binary heap, lazy deletion | O(E log V) | O(E) |
| Fibonacci heap | O(E + V log V) | O(V) |
The Fibonacci bound is the best known for comparison-based priority queues on general graphs. It beats a binary heap asymptotically when E is much larger than V, for example E ≈ V^1.5.
Why It Rarely Wins in Practice
- Constant factors. Each node carries parent, child, sibling pointers, a degree, and a mark bit. Following pointers causes cache misses, while a binary heap is a compact array.
- Amortization. The O(1) is an average over a sequence of operations. A single extract-min can take O(V) time while it consolidates trees, which is a problem for latency-sensitive code.
- Implementation effort. Cascading cuts and consolidation are easy to get subtly wrong.
- Better middle grounds. Pairing heaps and d-ary heaps (for example 4-ary) are simpler and usually faster on real road and network graphs.
Choosing a Strategy
| Situation | Reasonable choice |
|---|---|
| Python, typical sparse graph, short code | heapq with lazy deletion |
| Memory-constrained, many improvements per vertex | Indexed binary heap with decrease-key |
| Dense graph (E near V²) | Array-based O(V²) scan |
| Library or language provides a tuned decrease-key heap | Use it, but benchmark against lazy deletion |
| Theoretical bound matters, very large E/V ratio | Fibonacci or pairing heap |
Common Errors
- Forgetting the stale check in lazy deletion. Without
if u in visited: continue, a vertex is expanded once per stale entry. Distances stay correct, but the work blows up and predecessors may be overwritten needlessly. - Stale position map. In an indexed heap, any swap that skips updating
posleaves the map pointing at the wrong index, and a later decrease-key moves the wrong entry. - Non-comparable items in heapq tuples. If two entries tie on distance, heapq compares the vertices. Vertices that are objects without ordering raise
TypeError. Insert a counter as a tiebreaker:(dist, counter, vertex). The indexed heap above compares only keys, so it avoids this. - Calling decrease-key with a larger key. Some implementations corrupt the heap when that happens. The version above ignores it.
Exercise
In the lazy-deletion version, what is the largest number of entries the heap can ever contain for a graph with V vertices and E directed edges, and why does this not change the O(E log V) time bound?
Show answer
At most E + 1 entries: one for the source plus at most one push per edge, because each edge is relaxed only once, when its tail vertex is finalized. Each heap operation costs O(log E), and since E ≤ V², log E ≤ 2 log V, so O(E log E) = O(E log V).
Exercise
In dijkstradecreasekey, suppose you remove the line "if v in done: continue". With non-negative weights, can this cause a wrong answer or a crash?
Show answer
With non-negative weights, a finalized v always satisfies dist[v] <= d + w, so the elif branch is never taken and the code neither crashes nor changes results. It only does extra comparisons. With a negative edge, nd < dist[v] could hold for a finalized v, and decrease_key would raise KeyError because v is no longer in the position map.
Exercise
A graph has V = 1,000,000 vertices and E = 4,000,000 edges. Compare the binary-heap bound E log V with the Fibonacci-heap bound E + V log V using log2 V ≈ 20, and say which you would pick in practice.
Show answer
The binary heap gives about 4,000,000 × 20 = 80,000,000 operations. The Fibonacci heap gives about 4,000,000 + 1,000,000 × 20 = 24,000,000. That is roughly a 3x gap on paper, but the Fibonacci heap's pointer-heavy structure and larger constants usually erase it, so a binary heap (lazy deletion or a 4-ary heap) is the practical choice. Benchmark if the difference matters.