A Fibonacci heap lowers a key for a constant amortized price, where a binary heap pays log2 n. It is lazy: it cuts the node loose now and tidies up only when someone asks for the minimum.
Learn the heap of CLRS Chapter 19. Meet the forest, the lazy insert, the extract-min that tidies, cascading cuts, the potential t + 2m and the Fibonacci bound on degrees.
Press Insert a few times, then Extract-min, then Decrease-key. The pink bar is the real work of each operation. The green tick is its amortized charge, which stays small. Then we build the heap piece by piece.
You need a little Python, binary heaps and the idea of amortized cost. We build the rest from zero.
Re-taught from Chapter 19, Fibonacci Heaps, in the third edition of Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms (CLRS). The heap is from Fredman and Tarjan (1987). The toys and traces here are our own, and a script checked every number.
Keys are random. Real work counts the roots an operation touches and the cuts it makes. The charge is real work plus the change in t + 2m (Chapter 2). The grey dash is log2 n, the price of one binary-heap operation.
Chapter 0
Count the heap calls of a shortest-path search and find the one that dominates on dense graphs
A route planner runs Dijkstra's algorithm: it grows the set of places whose shortest distance is known, nearest first. It keeps the unsettled places in a priority queue. It makes two kinds of calls. EXTRACT-MIN takes out the nearest place, once per vertex. DECREASE-KEY lowers a neighbour's distance when a shorter road appears, up to once per edge.
Call the number of vertices V and the number of edges E. A binary heap pays about log2 V steps for each call of either kind.
T-bin equals V plus E, times log base 2 of V. T-Fib equals V times log base 2 of V, plus E.
With a binary heap, every one of the V + E calls pays log2 V. With a Fibonacci heap, only the V extract-mins pay it. The E key changes pay one step each.
With made-up numbers: V = 1,000 and E = 50,000, so log2 V is about 10. Tbin = 51,000 × 10 = 510,000. TFib = 10,000 + 50,000 = 60,000. That is 8.5 times less heap work.
Each bar is the heap work of one Dijkstra run. Drag the density and watch the binary-heap bar run away.
Worst-case counts from the two formulas above, with every edge causing one DECREASE-KEY. Chapter 8 counts what a real run does. Log scale.
Where does the saving come from? A Fibonacci heap does almost nothing on insert and on DECREASE-KEY. It lets its trees get messy and pays for the mess inside EXTRACT-MIN.
| Operation | Binary heap | Fibonacci heap |
|---|---|---|
| INSERT | O(log n) | O(1) |
| MINIMUM | O(1) | O(1) |
| UNION of two heaps | O(n) | O(1) |
| EXTRACT-MIN | O(log n) | O(log n) amortized |
| DECREASE-KEY | O(log n) | O(1) amortized |
| DELETE | O(log n) | O(log n) amortized |
The failure. The symptom is a Dijkstra run that slows down much faster than its vertex count on dense graphs. To measure it, count DECREASE-KEY calls against V log2 V. If they are far larger, the key changes are the bill.
Chapter 1
Meet the trees, the circular root list, the min pointer and the five fields of a node
A binary heap is one balanced tree packed in an array. A Fibonacci heap is a set of trees of any shape. Each tree is min-heap-ordered: every child's key is at least its parent's key. A node can have any number of children.
The roots sit in the root list, a circular doubly linked list. The heap keeps one pointer, H.min, to the root with the smallest key, and a count n of all nodes. The smallest key in a tree is its root, so the smallest key in the heap is one of the roots.
Tap any node. Turn on the sibling links to see the circular lists that join the roots and each set of children.
A fixed heap of 13 nodes in 3 trees. Node 5 is marked.
Each node stores five links and facts besides its key:
pythonclass FibNode: def __init__(self, key): self.key = key self.degree = 0 # number of children self.mark = False # lost a child since it last became a child? self.parent = None self.child = None # any one child; the rest are its siblings self.left = self.right = self # circular sibling list
The degree of a node is its number of children. The mark says the node lost one child since it last became a child; Chapter 4 uses it. With numbers: the device heap has t = 3 trees and n = 13 nodes. The root 2 has degree 3, and H.min points at it.
Why circular and doubly linked? Two such lists join with four pointer writes, whatever their lengths. One node leaves a list with two writes. That is what makes UNION and a cut cost O(1).
The failure. Code that forgets to update H.min after a change returns a wrong minimum. To catch it, assert after every operation that H.min holds the smallest root key. The fix is one comparison in each operation that adds a root.
Chapter 2
Add roots without tidying, and write down the debt with a potential
Three operations touch only the root list:
Insert a few keys, then union a second heap of 5, 12 and 8. No tree ever gets a child here.
Starts from inserts of 7, 3, 11, 1, 9. Real work: 1 step per insert, 1 per union.
Each new root is work that a later EXTRACT-MIN must do. To track that debt, call the number of trees t and the number of marked nodes m. The potential Φ is a number we compute from the heap's shape.
Phi of H equals t of H plus two times m of H.
Count the trees t. Count the marked nodes m and double it. Add the two.
The heap of Chapter 1 has t = 3 trees and m = 1 marked node, so Φ = 3 + 2 = 5.
The amortized cost ĉ of an operation is its real cost c plus the change in potential it causes.
c-hat equals c plus phi-after minus phi-before.
Charge the real cost c. If the operation adds potential, charge that too. If it uses potential up, subtract it.
INSERT: c = 1, and t goes up by 1, so Φafter − Φbefore = 1 and ĉ = 2. One step pays now, and one goes into Φ for later.
Add ĉ over a whole sequence and the potentials cancel in pairs: the total charge is the total real cost plus Φend − Φstart. The heap starts empty, at Φ = 0, and Φ is never negative. So the charges never undercount the real work.
The failure. A root list kept as a singly linked list makes UNION walk to the tail: O(n). To see it, time UNION at n and at 10n. The fix is the circular doubly linked list.
Chapter 3
Remove the minimum, promote its children, and link roots of equal degree until no two match
After six inserts the heap is six one-node trees. The next minimum could be any of them. EXTRACT-MIN removes the minimum, then tidies so that the next search is short.
The heap holds 3, 7, 11, 1, 9, 5, 13 as one-node trees. Press Step to remove the 1 and link the rest. The row of slots is the array A.
The device visits roots in list order. The real work counts every root before the removal plus the children of z.
Six one-node trees end as 3(7, 9(11)) and 5(13): degrees 2 and 1. How much did that cost? Call the number of roots before the call t and the largest degree a node can have in an n-node heap D. Chapter 7 shows D is at most about 1.44 log2 n.
c-hat is at most t plus D, plus D plus 1 minus t, which is 2 D plus 1.
The real cost grows with t, the roots piled up. The potential falls by almost t, because the piled-up roots collapse to D + 1. The two t's cancel, so the charge depends only on D.
In the device: t = 7 and z has no children, so c = 7. Two trees remain, so Φ falls from 7 to 2 and ĉ = 7 − 5 = 2. The limit for n = 7 is D = 4, so 2D + 1 = 9.
The inserts paid for this in advance. Each one saved one step in Φ, and CONSOLIDATE spends those steps.
The failure. A CONSOLIDATE that writes A[d] = x without the while loop overwrites trees, and keys vanish from the heap. To catch it, check after each EXTRACT-MIN that n matches a count of all nodes. The fix is the loop below: link, empty A[d], then try d + 1.
Chapter 4
Cut a node that beats its parent, mark the parent, and cascade when a parent loses a second child
Lower a key and it may now beat its parent. A binary heap swaps it up, one level at a time: O(log n). A Fibonacci heap cuts the node from its parent and moves it, with its subtree, to the root list. That is a few pointer writes.
Cuts alone are dangerous. A node could lose child after child and keep its place, so a tree with a big root degree could hold few nodes. Chapter 7 needs big degrees to mean big trees. The mark enforces it with three rules:
Use the two presets to follow the trace below. Or tap any node, choose a new key and press Lower.
A fixed start: 3 with children 15, 7(18) and the marked 9(11), plus a root 26. Keys can drop to 0.
Trace the presets. Lower 18 to 2: it beats 7, so cut 18. Node 7 had no mark, so mark it. One cut, t up 1, m up 1.
Then lower 11 to 1: cut 11 from 9. Node 9 is marked, so cut 9 as well. Node 3 is a root, so the cascade stops.
Call the number of cuts in one DECREASE-KEY c. Each cut adds a root. Every cut after the first unmarks a node, and the last step marks at most one.
Delta phi is at most c plus two times two minus c, which is 4 minus c.
Each cut adds one root but clears one mark worth 2, so it lowers Φ by 1. The real cost c rises by 1. Charge c + ΔΦ and the cuts cancel: at most 4 per call.
Lower 18 to 2: c = 1, ΔΦ = 1 + 2 = 3, so ĉ = 4. Lower 11 to 1: c = 2, t up 2, m down 1, so ΔΦ = 0 and ĉ = 2. A cascade of c = 9 has ΔΦ ≤ −5 and ĉ ≤ 4.
The failure. Code that cuts but never cascades still returns right answers. But trees can keep a big root degree with few nodes, so EXTRACT-MIN slows down. To catch it, log the largest root degree against logφ n from Chapter 7. The fix is the cascading cut.
Chapter 5
Lower the key below everything, then extract it
A task leaves the queue before its turn. You hold a pointer to its node, so you do not need to search. How do you remove it without breaking the heap?
DELETE(H, x) makes x the minimum and extracts it:
Tap a node, then press Delete. Watch phase 1 cut it loose and phase 2 extract it and consolidate.
A fixed start of 11 nodes: 3(5(9), 7, 12(14)) and 8(10, 15*(17, 20)).
Trace the delete of 15. Phase 1 sets its key to −∞ and cuts it, with 17 and 20, from 8. Node 8 is a root, so nothing is marked. Phase 2 removes it and promotes 17 and 20. CONSOLIDATE links 20 under 17 (both degree 0), then 17 under 8 (both degree 1). The result is 3(5(9), 7, 12(14)) and 8(10, 17(20)).
With numbers: Φ starts at 2 trees + 2 × 1 mark = 4. Phase 1 has real cost 1 and leaves Φ = 3, so it charges 0. Phase 2 has real cost 3 roots + 2 children = 5 and leaves Φ = 2, so it charges 4. The limit is 4 + (2D + 1) with D = 4 for n = 11: 13.
So DELETE costs O(1) + O(log n) = O(log n) amortized. A binary heap's delete is also O(log n), so here the Fibonacci heap wins nothing.
The failure. Code that uses a big negative number such as −109 in place of −∞ breaks when a real key is smaller. EXTRACT-MIN then removes the wrong node. To catch it, test with keys near the sentinel. The fix is float('-inf'), or a flag on the node.
Chapter 6
Change the weight on marks and watch the charge for a long cascade stay flat or grow
Think of Φ as coins on the heap. Each root holds one coin. Each marked node holds some coins too. Why two, and not one?
Follow one cut inside a cascade. It does one step of real work. It moves a marked node to the root list, and that new root needs its own coin for a future CONSOLIDATE. So the mark must pay for two things: the cut now, and the root coin later.
Pick the weight a on each mark, then drag the number of cuts. With a = 2 the charge stays at 4. With a = 1 it climbs.
The worst case of Chapter 4: c cuts, c − 1 marks cleared, and the last step marks one node.
Call the weight on each mark a, so Φ = t + a·m. A DECREASE-KEY with c cuts has real cost c. It adds c roots, clears c − 1 marks and sets 1.
c-hat equals 2 minus a, times c, plus 2 a.
Each cut costs 1 step and adds 1 root coin, and it frees a coins from a mark. If a is 2, the freed coins pay for both, and c drops out.
With c = 10: a = 1 gives ĉ = 10 + 2 = 12; a = 2 gives 0 + 4 = 4; a = 3 gives −10 + 6 = −4.
A larger a also works, but each new mark then costs more coins. So 2 is the smallest weight that keeps the charge constant. EXTRACT-MIN never adds a mark, so a does not change its charge.
The failure. A potential with weight 1 still gives a total that never undercounts. But the charge per DECREASE-KEY grows with the cascade, so the O(1) claim is false. To catch it, log the largest charge over random runs of growing size. If it grows, the potential is wrong.
Chapter 7
Show that a big degree forces a big tree, and find the Fibonacci numbers in the smallest one
The charge 2D + 1 of Chapter 3 is only small if D, the largest degree, is small. Why can't one root collect a hundred children? Because the marks force a node of big degree to own a big subtree.
Take a node x of degree k. List its children in the order they were linked, oldest first. When child number i was linked, x already had at least i − 1 children. CONSOLIDATE links only equal degrees, so that child also had at least i − 1. Since then it lost at most one child, or a cascade would have cut it. So child i has degree at least i − 2.
Call sk the fewest nodes a subtree can have when its root has degree k.
s-k is at least 2 plus the sum over i from 0 to k minus 2 of s-i.
Count the root and its first child. Then add the smallest subtree for degrees 0, 1, up to k − 2, one for each later child.
s0 = 1 and s1 = 2. Then s2 = 2 + 1 = 3, s3 = 2 + 1 + 2 = 5, and s4 = 2 + 1 + 2 + 3 = 8. These are the Fibonacci numbers Fk+2.
Drag k. The tree gives its root k children of degrees 0, 0, 1, …, k − 2, each as sparse as allowed.
The shape follows the lemma at its limit. Numbers in each node are that node's degree.
The Fibonacci numbers grow like powers of the golden ratio φ = (1 + √5)/2 ≈ 1.618: Fk+2 ≥ φk. A subtree cannot hold more than all n nodes, so φk ≤ n.
D of n is at most the floor of log base phi of n.
Find how many times you can multiply by 1.618 and stay at or below n. No node can have more children than that.
For n = 1,000: logφ 1,000 = 14.35, so D = 14, against log2 1,000 = 9.97. For n = 1,000,000: D = 28, against 19.93.
| Degree k | Fewest nodes sk | φk |
|---|---|---|
| 0 | 1 | 1.00 |
| 2 | 3 | 2.62 |
| 4 | 8 | 6.85 |
| 6 | 21 | 17.94 |
| 8 | 55 | 46.98 |
| 29 | 1,346,269 | 1,149,851 |
The failure. Code that sizes the array A of CONSOLIDATE with log2 n makes it too small. A heap of 1,000 nodes can need slot 14, but log2 gives 10 slots. The symptom is an index error after many decrease-keys. The fix is ⌊logφ n⌋ + 1 slots, or a dictionary.
Chapter 8
Count the key changes a real run makes, and weigh them against the heap's constant costs
Back to the route planner. With a Fibonacci heap, Dijkstra pays V extract-mins at O(log V) each. It pays at most E key changes at O(1) each, so the total is O(V log V + E). Prim's algorithm for minimum spanning trees makes the same calls and gets the same bound.
But Chapter 0 assumed every edge lowers a key. Does it? Run Dijkstra and count.
Each press runs Dijkstra on a new random graph of 1,000 vertices. Drag the density and compare the edges with the key changes they cause.
Random directed edges with weights uniform on 0 to 1, from vertex 0. Work estimates: binary (V + K) log2 V, Fibonacci V log2 V + K, for K key changes.
With random weights, few edges win. In our runs at 50 edges per vertex, 2,524 of 50,000 edges lowered a key (mean of 5 graphs). At 200 per vertex it was 3,876 of 200,000. The heap work was then about 35,000 steps for a binary heap and 12,500 for a Fibonacci heap. That is 2.8 times, not the 8.5 of Chapter 0.
The constants decide the rest:
Python's heapq has no DECREASE-KEY. Its documentation suggests pushing a new entry and skipping stale ones when they come out. Dijkstra then pushes up to E entries.
| Heap | Insert | Extract-min | Decrease-key | Union |
|---|---|---|---|---|
| Binary | O(log n) | O(log n) | O(log n) | O(n) |
| d-ary | O(logd n) | O(d logd n) | O(logd n) | O(n) |
| Binomial | O(1) amortized | O(log n) | O(log n) | O(log n) |
| Fibonacci (1987) | O(1) | O(log n) amortized | O(1) amortized | O(1) |
| Pairing (1986) | O(1) | O(log n) amortized | exact bound open | O(1) |
| Brodal (1996), strict Fibonacci (2012) | O(1) worst case | O(log n) worst case | O(1) worst case | O(1) worst case |
The failure. A team swaps in a Fibonacci heap for a sparse road graph and the planner gets slower. To measure first, count key changes K against V log2 V. If K is not far larger, keep the binary or 4-ary heap.
Chapter 9
Keep the terms, the numbers, the checks and the code in one place
A Fibonacci heap is a forest of min-heap-ordered trees with a pointer to the smallest root. INSERT and UNION add roots and do nothing else. EXTRACT-MIN removes the minimum and links roots of equal degree. DECREASE-KEY cuts a node loose, and marks with cascading cuts keep degrees at most logφ n. The potential t + 2m proves the bounds: O(1) amortized for everything except EXTRACT-MIN and DELETE, which are O(log n).
| Term | Meaning |
|---|---|
| Root list | Circular doubly linked list of the tree roots |
| H.min | Pointer to the root with the smallest key |
| Degree | Number of children of a node |
| Link | Make the larger of two equal-degree roots a child of the smaller |
| Consolidate | Link roots until no two share a degree |
| Cut | Move a node and its subtree to the root list, unmarked |
| Mark | A non-root node that lost one child since it became a child |
| Cascading cut | A marked node that loses a second child is cut too, and so on upward |
| Potential Φ | t + 2m: trees plus twice the marked nodes |
| What | Number | Why it matters |
|---|---|---|
| Dijkstra, V = 1,000, E = 50,000 | 510,000 against 60,000 steps | The worst-case gap of 8.5 times |
| Consolidating 7 one-node roots | real 7, charge 2 | Φ falls from 7 to 2 and pays |
| Lower 18 to 2, then 11 to 1 | charges 4 and 2 | No DECREASE-KEY charges more than 4 |
| Largest degree, n = 1,000 | 14 (log2: 9.97) | The array A needs 15 slots |
| Largest degree, n = 106 | 28 (log2: 19.93) | 1.44 times log2 n |
| Fewest nodes for degree 0 to 6 | 1, 2, 3, 5, 8, 13, 21 | The Fibonacci numbers Fk+2 |
| Real key changes, 50 edges per vertex | 2,524 of 50,000 | Worst-case counts overstate the gain |
heapq.A Python list stands in for each circular list, so remove is not O(1) here. The logic is the real one.
pythonimport math class Node: def __init__(self, key): self.key, self.mark, self.parent, self.kids = key, False, None, [] class FibHeap: def __init__(self): self.roots, self.min, self.n = [], None, 0 def insert(self, key): # O(1): one new root x = Node(key) self.roots.append(x); self.n += 1 if self.min is None or key < self.min.key: self.min = x return x # keep this handle for decrease_key def extract_min(self): # O(log n) amortized z = self.min for c in z.kids: c.parent, c.mark = None, False self.roots.remove(z); self.roots += z.kids; self.n -= 1 A = {} # degree -> the one root with it for x in list(self.roots): d = len(x.kids) while d in A: # a clash: link, then carry y = A.pop(d) if y.key < x.key: x, y = y, x y.parent, y.mark = x, False x.kids.append(y); d += 1 A[d] = x self.roots = list(A.values()) self.min = min(self.roots, key=lambda r: r.key, default=None) return z.key def decrease_key(self, x, k): # O(1) amortized x.key = k y = x.parent if y is not None and k < y.key: self._cut(x, y) while y.parent is not None: # the cascading cut if not y.mark: y.mark = True; break z = y.parent; self._cut(y, z); y = z if k < self.min.key: self.min = x def _cut(self, x, y): y.kids.remove(x); x.parent, x.mark = None, False self.roots.append(x) def delete(self, x): self.decrease_key(x, -math.inf); self.extract_min()
Now press Present or Teach. Explain from memory a consolidation, a cascading cut, the potential t + 2m and the degree bound. Then go back to the hero, insert eight keys, extract the minimum, and say why the charge is so much smaller than the pink bar.
This lesson re-teaches Chapter 19, Fibonacci Heaps, in the third edition of Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms. The heap is from Michael Fredman and Robert Tarjan, "Fibonacci heaps and their uses in improved network optimization algorithms", Journal of the ACM, 1987. The toys, traces and Dijkstra counts here are our own.