Lesson 5 · Non-linear structures

Fibonacci Heap

A Fibonacci heap is a collection of heap-ordered trees that postpones all tidying to extract-min, giving O(1) amortized insert, union and decrease-key and O(log n) amortized extract-min.

Fibonacci Heap concept diagramFive heap-ordered trees whose roots 23, 7, 3, 17 and 24 are joined by a dashed root list that wraps around underneath into a ring. A min pointer marks root 3, which has degree 3 with children 18, 52 and 38. Nodes 18 and 26 are orange because they are marked: each has lost a child. Children of one parent are also joined by dashed sibling links.23739185241383301735264624root list: a circular, doubly linked ring of tree rootsmindegree 3marked: lost one child since it became a childsibling ring under each parent
1

A Lazy Priority Queue

A Fibonacci heap is a mergeable priority queue made of a collection of trees, each obeying the min-heap property: every node's key is no smaller than its parent's. It was introduced by Michael Fredman and Robert Tarjan in 1984 to speed up graph algorithms that call decrease-key many times.

Its idea is laziness. Insert and union just add trees to a list, and decrease-key just cuts a subtree off. All the restructuring is postponed to extract-min, which merges trees until the list is short. Using amortized analysis, every operation except extract-min and delete costs O(1) amortized, and those two cost O(log n) amortized.

  • A lazy relative of the binomial heap: trees need not be binomial and are merged only on demand
  • Bounds are amortized: one extract-min can take O(n) time
  • Supports insert, find-min, union, extract-min, decrease-key and delete
2

Root List, Child Lists and Marks

The trees' roots are joined in a circular, doubly linked root list, and the heap keeps a pointer H.min to the root with the smallest key. The children of every node are joined in the same way, in a circular, doubly linked child list, and each node points to its parent and to one of its children. Circular doubly linked lists let a node be spliced in or out, and two lists be concatenated, in O(1).

Each node also stores its degree (number of children) and a boolean mark. A node is marked when it loses a child after it became a child of its current parent. Roots are never marked.

  • Node fields: key, parent (null for a root), child (any one child), left and right (neighbours in the ring), degree and mark
  • Heap fields: H.min (minimum root) and H.n (number of nodes)
  • The root list may hold many trees of the same degree until the next extract-min
  • Unlike a binary heap, there is no array and no fixed shape
3

The Six Operations

Four of the six operations do almost no work. The cost is concentrated in extract-min, the only operation that shortens the root list. All costs below are amortized.

  • Insert(x) – O(1): make x a one-node tree, add it to the root list, update H.min
  • Find-min – O(1): return H.min
  • Union(H₁, H₂) – O(1): concatenate the two root lists and keep the smaller min
  • Extract-min – O(log n): remove H.min, promote its children to roots, consolidate
  • Decrease-key(x, k) – O(1): lower the key; if heap order breaks, cut x and cascade
  • Delete(x) – O(log n): decrease-key(x, −∞), then extract-min
  • Insert and union never merge trees, so n inserts leave n roots
  • The listing inserts 7, 24, 17, 23, 3, 18, 52, 38, 41: nine roots, min = 3
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Root listCircular, doubly linked list of the roots of all trees.
  • DegreeNumber of children of a node.
  • MarkSet when a non-root node loses a child; cleared when it becomes a root or is linked.
  • Cascading cutCutting a marked parent after it loses a second child, repeated upward.

Formulas

  • PotentialΦ(H) = t(H) + 2·m(H): trees plus twice the marked nodes.
  • Degree boundsize(x) ≥ F(deg(x) + 2) ≥ φ^deg(x).
  • Maximum degreeD(n) ≤ log_φ n ≈ 1.44 log₂ n.
  • DijkstraO(E + V log V) with a Fibonacci heap.
Implementation

Code in Python, C++ and Java

class Node:
    def __init__(self, key):
        self.key = key
        self.parent = None
        self.children = []
        self.mark = False


class FibonacciHeap:
    def __init__(self):
        self.roots = []
        self.min = None
        self.n = 0
        self.verbose = True

    def log(self, message):
        if self.verbose:
            print("  " + message)

    def insert(self, key):
        # O(1): a new one-node tree joins the root list; nothing is merged.
        x = Node(key)
        self.roots.append(x)
        if self.min is None or key < self.min.key:
            self.min = x
        self.n += 1
        return x

    def extract_min(self):
        z = self.min
        self.roots.remove(z)
        for child in z.children:
            child.parent = None
            child.mark = False
            self.roots.append(child)
        self.n -= 1
        self.consolidate()
        return z.key

    def consolidate(self):
        # Link roots of equal degree until every degree appears at most once.
        table = {}
        for x in self.roots:
            d = len(x.children)
            while d in table:
                y = table.pop(d)
                if y.key < x.key:
                    x, y = y, x
                self.log(f"link {y.key} under {x.key} (degree {d} + degree {d})")
                y.parent = x
                y.mark = False
                x.children.append(y)
                d += 1
            table[d] = x
        self.roots = [table[d] for d in sorted(table)]
        self.min = None
        for r in self.roots:
            if self.min is None or r.key < self.min.key:
                self.min = r

    def decrease_key(self, x, key):
        x.key = key
        p = x.parent
        if p and x.key < p.key:
            self.cut(x, p)
            self.cascading_cut(p)
        if x.key < self.min.key:
            self.min = x

    def cut(self, x, p):
        # Children in a list make this O(degree) = O(log n);
        # a circular doubly linked child list makes it O(1).
        p.children.remove(x)
        x.parent = None
        x.mark = False
        self.roots.append(x)
        self.log(f"cut {x.key} from {p.key}")

    def cascading_cut(self, y):
        z = y.parent
        if z is None:
            return
        if not y.mark:
            y.mark = True
            self.log(f"mark {y.key}")
        else:
            self.cut(y, z)
            self.cascading_cut(z)


def show(node):
    s = str(node.key) + ("*" if node.mark else "")
    if node.children:
        s += "(" + " ".join(show(c) for c in node.children) + ")"
    return s


def report(heap):
    print("  roots: " + "  ".join(show(r) for r in heap.roots))
    print(f"  min = {heap.min.key}, n = {heap.n}")


heap = FibonacciHeap()
nodes = {}
print("insert 7 24 17 23 3 18 52 38 41")
for k in [7, 24, 17, 23, 3, 18, 52, 38, 41]:
    nodes[k] = heap.insert(k)
report(heap)

print("extract_min")
print(f"  returned {heap.extract_min()}")
report(heap)

for old, new in [(41, 5), (38, 12), (52, 2)]:
    print(f"decrease_key {old} -> {new}")
    heap.decrease_key(nodes[old], new)
    report(heap)

print("extract_min")
print(f"  returned {heap.extract_min()}")
report(heap)

heap.verbose = False
order = []
while heap.n:
    order.append(str(heap.extract_min()))
print("drain: " + " ".join(order))
#include <algorithm>
#include <cstdio>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>

struct Node {
    int key;
    Node* parent = nullptr;
    std::vector<Node*> children;
    bool mark = false;
    explicit Node(int k) : key(k) {}
};

struct FibonacciHeap {
    std::vector<Node*> roots;
    Node* min = nullptr;
    int n = 0;
    bool verbose = true;
    std::vector<std::unique_ptr<Node>> owned;

    void log(const std::string& message) const {
        if (verbose) std::printf("  %s\n", message.c_str());
    }

    Node* insert(int key) {
        // O(1): a new one-node tree joins the root list; nothing is merged.
        owned.push_back(std::make_unique<Node>(key));
        Node* x = owned.back().get();
        roots.push_back(x);
        if (!min || key < min->key) min = x;
        n++;
        return x;
    }

    int extractMin() {
        Node* z = min;
        roots.erase(std::find(roots.begin(), roots.end(), z));
        for (Node* child : z->children) {
            child->parent = nullptr;
            child->mark = false;
            roots.push_back(child);
        }
        n--;
        consolidate();
        return z->key;
    }

    void consolidate() {
        // Link roots of equal degree until every degree appears at most once.
        std::map<int, Node*> table;
        for (Node* x : roots) {
            int d = (int)x->children.size();
            while (table.count(d)) {
                Node* y = table[d];
                table.erase(d);
                if (y->key < x->key) std::swap(x, y);
                log("link " + std::to_string(y->key) + " under " + std::to_string(x->key) + " (degree " +
                    std::to_string(d) + " + degree " + std::to_string(d) + ")");
                y->parent = x;
                y->mark = false;
                x->children.push_back(y);
                d++;
            }
            table[d] = x;
        }
        roots.clear();
        min = nullptr;
        for (auto& [d, r] : table) {
            roots.push_back(r);
            if (!min || r->key < min->key) min = r;
        }
    }

    void decreaseKey(Node* x, int key) {
        x->key = key;
        Node* p = x->parent;
        if (p && x->key < p->key) {
            cut(x, p);
            cascadingCut(p);
        }
        if (x->key < min->key) min = x;
    }

    void cut(Node* x, Node* p) {
        // Children in a vector make this O(degree) = O(log n);
        // a circular doubly linked child list makes it O(1).
        p->children.erase(std::find(p->children.begin(), p->children.end(), x));
        x->parent = nullptr;
        x->mark = false;
        roots.push_back(x);
        log("cut " + std::to_string(x->key) + " from " + std::to_string(p->key));
    }

    void cascadingCut(Node* y) {
        Node* z = y->parent;
        if (!z) return;
        if (!y->mark) {
            y->mark = true;
            log("mark " + std::to_string(y->key));
        } else {
            cut(y, z);
            cascadingCut(z);
        }
    }
};

std::string show(const Node* node) {
    std::string s = std::to_string(node->key) + (node->mark ? "*" : "");
    if (!node->children.empty()) {
        s += "(";
        for (size_t i = 0; i < node->children.size(); i++) s += (i ? " " : "") + show(node->children[i]);
        s += ")";
    }
    return s;
}

void report(const FibonacciHeap& heap) {
    std::string line;
    for (size_t i = 0; i < heap.roots.size(); i++) line += (i ? "  " : "") + show(heap.roots[i]);
    std::printf("  roots: %s\n", line.c_str());
    std::printf("  min = %d, n = %d\n", heap.min->key, heap.n);
}

int main() {
    FibonacciHeap heap;
    std::map<int, Node*> nodes;
    std::printf("insert 7 24 17 23 3 18 52 38 41\n");
    for (int k : {7, 24, 17, 23, 3, 18, 52, 38, 41}) nodes[k] = heap.insert(k);
    report(heap);

    std::printf("extract_min\n");
    int got = heap.extractMin();
    std::printf("  returned %d\n", got);
    report(heap);

    for (auto [oldKey, newKey] : std::vector<std::pair<int, int>>{{41, 5}, {38, 12}, {52, 2}}) {
        std::printf("decrease_key %d -> %d\n", oldKey, newKey);
        heap.decreaseKey(nodes[oldKey], newKey);
        report(heap);
    }

    std::printf("extract_min\n");
    got = heap.extractMin();
    std::printf("  returned %d\n", got);
    report(heap);

    heap.verbose = false;
    std::string order;
    while (heap.n) order += (order.empty() ? "" : " ") + std::to_string(heap.extractMin());
    std::printf("drain: %s\n", order.c_str());
    return 0;
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    static class Node {
        int key;
        Node parent;
        List<Node> children = new ArrayList<>();
        boolean mark;

        Node(int key) {
            this.key = key;
        }
    }

    static class FibonacciHeap {
        List<Node> roots = new ArrayList<>();
        Node min;
        int n;
        boolean verbose = true;

        void log(String message) {
            if (verbose) System.out.println("  " + message);
        }

        Node insert(int key) {
            // O(1): a new one-node tree joins the root list; nothing is merged.
            Node x = new Node(key);
            roots.add(x);
            if (min == null || key < min.key) min = x;
            n++;
            return x;
        }

        int extractMin() {
            Node z = min;
            roots.remove(z);
            for (Node child : z.children) {
                child.parent = null;
                child.mark = false;
                roots.add(child);
            }
            n--;
            consolidate();
            return z.key;
        }

        void consolidate() {
            // Link roots of equal degree until every degree appears at most once.
            TreeMap<Integer, Node> table = new TreeMap<>();
            for (Node root : roots) {
                Node x = root;
                int d = x.children.size();
                while (table.containsKey(d)) {
                    Node y = table.remove(d);
                    if (y.key < x.key) {
                        Node t = x;
                        x = y;
                        y = t;
                    }
                    log("link " + y.key + " under " + x.key + " (degree " + d + " + degree " + d + ")");
                    y.parent = x;
                    y.mark = false;
                    x.children.add(y);
                    d++;
                }
                table.put(d, x);
            }
            roots = new ArrayList<>(table.values());
            min = null;
            for (Node r : roots) {
                if (min == null || r.key < min.key) min = r;
            }
        }

        void decreaseKey(Node x, int key) {
            x.key = key;
            Node p = x.parent;
            if (p != null && x.key < p.key) {
                cut(x, p);
                cascadingCut(p);
            }
            if (x.key < min.key) min = x;
        }

        void cut(Node x, Node p) {
            // Children in an ArrayList make this O(degree) = O(log n);
            // a circular doubly linked child list makes it O(1).
            p.children.remove(x);
            x.parent = null;
            x.mark = false;
            roots.add(x);
            log("cut " + x.key + " from " + p.key);
        }

        void cascadingCut(Node y) {
            Node z = y.parent;
            if (z == null) return;
            if (!y.mark) {
                y.mark = true;
                log("mark " + y.key);
            } else {
                cut(y, z);
                cascadingCut(z);
            }
        }
    }

    static String show(Node node) {
        StringBuilder s = new StringBuilder(node.key + (node.mark ? "*" : ""));
        if (!node.children.isEmpty()) {
            List<String> parts = new ArrayList<>();
            for (Node c : node.children) parts.add(show(c));
            s.append("(").append(String.join(" ", parts)).append(")");
        }
        return s.toString();
    }

    static void report(FibonacciHeap heap) {
        List<String> parts = new ArrayList<>();
        for (Node r : heap.roots) parts.add(show(r));
        System.out.println("  roots: " + String.join("  ", parts));
        System.out.println("  min = " + heap.min.key + ", n = " + heap.n);
    }

    public static void main(String[] args) {
        FibonacciHeap heap = new FibonacciHeap();
        Map<Integer, Node> nodes = new HashMap<>();
        System.out.println("insert 7 24 17 23 3 18 52 38 41");
        for (int k : new int[] {7, 24, 17, 23, 3, 18, 52, 38, 41}) nodes.put(k, heap.insert(k));
        report(heap);

        System.out.println("extract_min");
        System.out.println("  returned " + heap.extractMin());
        report(heap);

        for (int[] change : new int[][] {{41, 5}, {38, 12}, {52, 2}}) {
            System.out.println("decrease_key " + change[0] + " -> " + change[1]);
            heap.decreaseKey(nodes.get(change[0]), change[1]);
            report(heap);
        }

        System.out.println("extract_min");
        System.out.println("  returned " + heap.extractMin());
        report(heap);

        heap.verbose = false;
        List<String> order = new ArrayList<>();
        while (heap.n > 0) order.add(String.valueOf(heap.extractMin()));
        System.out.println("drain: " + String.join(" ", order));
    }
}
Watch it run

Step through it

Running on insert 7 24 17 23 3 18 52 38 41; extract-min; decrease 41→5, 38→12, 52→2; extract-min

7241723mininsert: add a root, update minO(1) actual
Step 1

Insert 7, 24, 17, 23: each is a new one-node root

Insert does no restructuring at all. The new node is spliced into the root list next to the others and compared with min. That is O(1) actual time, which is why the heap can defer all tidying to extract-min.

Output
1 / 18
4

Extract-Min and Consolidation

  1. Remove – take z = H.min out of the root list.
  2. Promote – add each child of z to the root list and clear its parent pointer.
  3. Consolidate – for each root x of degree d: while A[d] holds a root y, link the larger of x and y under the smaller, clear A[d] and increase d; then store the result in A[d].
  4. Rebuild – the roots left in A form the new root list; set H.min to the smallest one.

Extract-min removes the minimum root and makes each of its children a root. Then it consolidates: it links roots of equal degree until every degree occurs at most once. A link makes the root with the larger key a child of the root with the smaller key, which keeps heap order and raises the winner's degree by one.

Consolidation uses a degree table A[0..D(n)], where D(n) is the largest possible degree. Each root is placed in A[its degree]; if that slot is taken, the two are linked and the result tries the next slot, just like carrying in binary addition. When every root has been placed, the table holds the new root list and the smallest of them becomes H.min.

  • In the listing, the 8 roots left after extracting 3 end as one tree of degree 3 after 7 links; the tracer shows each one
  • Actual cost is O(D(n) + number of roots); the roots were prepaid by the inserts that made them
  • After consolidation there are at most D(n) + 1 roots
5

Decrease Key and the Cascading Cut

  1. Lower – set x.key = k and update H.min if k is smaller.
  2. Cut – if x has a parent y and k < y.key, remove x from y's child list, add it to the root list and unmark it.
  3. Cascade – if y is not a root: mark y if it was unmarked; otherwise cut y as well and repeat with y's parent.

Decrease-key lowers the key of node x. If x is a root, or its new key is still no smaller than its parent's, nothing else happens. Otherwise heap order is broken, and instead of sifting x up, the heap cuts x from its parent and makes it a new unmarked root.

Then comes the cascading cut. If the parent y was unmarked, it is marked: it has lost one child. If y was already marked, it has now lost two, so y is cut and moved to the root list too, and the same test repeats on y's parent, up the tree until an unmarked node or a root is reached. This rule stops a tree from losing so many nodes that its degree no longer says anything about its size.

  • In the listing, 41 → 5 marks 38, 38 → 12 marks 18, and 52 → 2 finds 18 already marked, so 18 is cut too and the cascade stops at the root 7
  • Each cascading cut unmarks a node, and the marks paid for it, so decrease-key is O(1) amortized
  • Delete is decrease-key to −∞ followed by extract-min
6

Amortized Costs from the Potential Function

The bounds come from the potential method with Φ(H) = t(H) + 2·m(H), where t is the number of trees in the root list and m the number of marked nodes. Insert raises Φ by 1, so it is O(1). Extract-min does O(D(n) + t) actual work but leaves at most D(n) + 1 roots, so the drop in Φ pays for the t part: O(D(n)) = O(log n) amortized. Decrease-key with c cascading cuts does O(c) work, adds c roots and removes about c marks, so ΔΦ ≤ 4 − c and the amortized cost is O(1).

Priority queue costs: binary heap, binomial heap and Fibonacci heap
OperationBinary heap (worst)Binomial heap (worst)Fibonacci heap (amortized)
InsertO(log n)O(log n)O(1)
Find-minO(1)O(log n), O(1) with a min pointerO(1)
Extract-minO(log n)O(log n)O(log n)
UnionO(n)O(log n)O(1)
Decrease-keyO(log n)O(log n)O(1)
DeleteO(log n)O(log n)O(log n)
  • Space: O(n), with four pointers, a degree and a mark per node
  • Worst case for a single extract-min is O(n), e.g. right after n inserts
7

Where the Name Comes From

The name comes from the proof that the maximum degree D(n) is O(log n). Order the children of a node x by the time they were linked to it. When the i-th child was linked, x already had at least i − 1 children, and links only join equal degrees, so that child also had degree at least i − 1. Since then it has lost at most one child, or it would have been cut, so its degree is still at least i − 2.

From this, the smallest possible tree with a root of degree k has s_k ≥ F(k + 2) nodes, where F is the Fibonacci sequence 1, 1, 2, 3, 5, 8, 13, …: degrees 0 to 5 need at least 1, 2, 3, 5, 8 and 13 nodes And F(k + 2) ≥ φᵏ with φ = (1 + √5)/2 ≈ 1.618. So n ≥ φᵏ, which gives D(n) ≤ log_φ n ≈ 1.44 log₂ n.

  • Without marks and cascading cuts, trees could lose most of their nodes and D(n) would not be O(log n)
  • A binomial tree of degree k has exactly 2ᵏ nodes; a Fibonacci heap only guarantees F(k + 2)
8

When It Pays Off

The structure pays off when an algorithm performs many more decrease-key operations than extract-min operations. That is exactly the pattern of shortest-path and spanning-tree algorithms on dense graphs.

Algorithms sped up by a Fibonacci heap
AlgorithmBinary heapFibonacci heap
Dijkstra's shortest pathsO((V + E) log V)O(E + V log V)
Prim's minimum spanning treeO((V + E) log V)O(E + V log V)
Johnson's all-pairs shortest pathsO(VE log V)O(V² log V + VE)
Merging many priority queuesO(n) per unionO(1) per union
  • Drawbacks: large constant factors, four pointers per node and poor cache behaviour
  • In practice a binary heap or pairing heap is often faster unless the graph is large and dense
  • Practise the algorithm it speeds up: Network Delay Time