The Fibonacci Heap

Matt George

Fractional CTO · Founder of Injuria.ai

•22 min read•

The Fibonacci Heap

The Fibonacci heap is a highly theoretical and asymptotically optimal data structure used to implement a priority queue. It consists of a forest of heap-ordered trees and is designed to support a specific set of operations in constant amortized time. By deferring structural maintenance until absolutely necessary, the Fibonacci heap achieves time bounds that strictly improve upon earlier priority queue designs, such as binary heaps and binomial queues. The data structure is named after the Fibonacci sequence, which appears in the mathematical proof bounding the maximum degree of any node within the heap.

Developed in the early 1980s, the primary motivation for the Fibonacci heap was to accelerate fundamental graph algorithms. Algorithms that compute shortest paths or minimum spanning trees rely heavily on priority queues to repeatedly select the next closest vertex. The ability to decrease the priority of a vertex in constant time allows these graph algorithms to run in near-linear time relative to the number of edges. This theoretical discovery established a new baseline for the asymptotic complexity of network optimization problems.

Despite its theoretical optimality, the Fibonacci heap is rarely the preferred choice in practical software engineering. The data structure requires complex pointer manipulation, maintains multiple pointers per node, and incurs high constant-factor overhead. Consequently, simpler structures often outperform it on modern hardware due to better cache locality and lower memory overhead. Nevertheless, the Fibonacci heap remains a foundational topic in computer science, having inspired decades of subsequent research into advanced data structures and amortized analysis.

Definition and the Problem it Solves

A priority queue is an abstract data type that stores a collection of elements, each associated with a numerical key or priority. The standard operations required by a priority queue include inserting new elements, finding the element with the minimum key, and removing the minimum element. Many advanced applications also require a decrease-key operation, which lowers the key of a specific element already present in the queue.[28]

In graph algorithms like Dijkstra's algorithm for single-source shortest paths Dijkstra, 1959[1] and Prim's algorithm for minimum spanning trees, the priority queue stores vertices. The key of a vertex represents its tentative distance from the source node or the growing spanning tree. As the algorithm explores the graph, it frequently discovers shorter paths to known vertices, necessitating a decrease-key operation. For a graph with $V$ vertices and $E$ edges, these algorithms perform exactly $V$ extract-min operations and up to $E$ decrease-key operations.

In graph theory, the density of a graph refers to the ratio of edges to vertices. A dense graph is one where the number of edges $E$ is close to the maximum possible number of edges, making $E \approx O(V^2)$. A sparse graph is one where the number of edges is much closer to the number of vertices, making $E \approx O(V)$.

Using a standard binary heap, both extract-min and decrease-key require $O(\log V)$ time, leading to a total running time of $O(E \log V + V \log V)$.[29] Because dense graphs can have up to $O(V^2)$ edges, the $E \log V$ term strictly dominates the running time. The Fibonacci heap solves this bottleneck by performing decrease-key in $O(1)$ amortized time, while keeping extract-min at $O(\log V)$ amortized time Fredman and Tarjan, 1987[2]. This reduces the total time complexity of Dijkstra's and Prim's algorithms to $O(E + V \log V)$, which is asymptotically optimal for comparison-based shortest-path algorithms Cormen et al., Introduction to Algorithms[3].[30] For dense graphs, this effectively reduces the time complexity from $O(V^2 \log V)$ to $O(V^2)$, stripping away the logarithmic factor entirely.

The impact of this improvement extends to all-pairs shortest path algorithms as well. Johnson's algorithm, which computes the shortest paths between all pairs of vertices in a sparse, edge-weighted directed graph that may contain negative edge weights, relies on Dijkstra's algorithm as a subroutine Johnson, 1977[4]. By reweighting the edges using the Bellman-Ford algorithm, Johnson's algorithm executes Dijkstra's algorithm exactly $V$ times. When implemented with a binary heap, Johnson's algorithm runs in $O(V E \log V)$ time. By substituting a Fibonacci heap, the time complexity drops to $O(V^2 \log V + V E)$, making it significantly faster for sparse graphs where $E$ is much smaller than $V^2$.

Mechanism and Operations

The Fibonacci heap is implemented as a collection, or forest, of heap-ordered trees. Unlike binomial heaps, where trees are rigid and perfectly balanced Vuillemin, 1978[5], the trees in a Fibonacci heap are flexible and unordered. The heap-order property simply dictates that the key of any child node must be greater than or equal to the key of its parent. This guarantees that the minimum element in any tree is always located at its root.

To achieve constant time operations, the data structure relies heavily on circular, doubly linked lists. Each node contains a pointer to its parent, a pointer to any one of its children, and pointers to its left and right siblings. The children of a given node are linked together in a circular doubly linked list, as are the roots of all the trees in the forest. This pointer-heavy representation allows entire subtrees to be detached and spliced into new positions in $O(1)$ time. Furthermore, each node stores its degree, which is the number of children it has, and a boolean mark bit used during decrease-key operations.

The data structure operates on the principle of lazy execution. Instead of maintaining a strict structure after every operation, the Fibonacci heap simply concatenates elements and defers the costly work of consolidating trees until an extract-min operation forces it to do so. The heap maintains a single pointer to the root node containing the minimum key, known as the minimum node.

Core Operations

The insert operation creates a new element as a single-node tree. This new node is inserted into the root list of the forest by updating the sibling pointers. The pointer to the minimum element is updated if the new key is smaller than the current minimum. Because no restructuring occurs, this operation takes $O(1)$ actual time.

The find-min operation is trivial. The structure maintains a direct pointer to the root containing the minimum key, allowing this operation to complete in $O(1)$ time.

The union operation merges two Fibonacci heaps by concatenating their circular doubly linked root lists. The minimum pointer is updated to point to the smaller of the two minimums. Like insertion, this takes $O(1)$ actual time because it only requires updating a few pointers.

The extract-min operation is the most complex procedure in the Fibonacci heap. It begins by removing the minimum node from the root list and promoting all of its children to the root list. The minimum pointer is then temporarily updated to an arbitrary root. Following this removal, a consolidation phase occurs to reduce the number of trees in the forest.

The consolidation algorithm initializes an array of pointers to roots, indexed by degree. The size of this array is bounded by the maximum possible degree of any node, denoted as $D(n) \le \lfloor \log_{\phi} n \rfloor$. For any practical application, $n$ is limited by the memory capacity of the computer. Even if a Fibonacci heap contained one trillion elements, the maximum degree would be less than 60. Therefore, the degree array requires a negligible amount of memory, typically just an array of 64 pointers, making the consolidation phase highly efficient in terms of auxiliary space.

The algorithm iterates through the root list. If two roots have the same degree, they are merged. The root with the larger key becomes a child of the root with the smaller key, and the degree of the new parent increases by one. The algorithm places the new merged tree back into the array at the next degree index, potentially triggering a chain reaction of merges if another tree of that new degree already exists. This merging continues until no two roots in the root list have the same degree. Finally, the algorithm scans the array to reconstruct the root list and find the new minimum node. The consolidation takes $O(\log n)$ amortized time.

The decrease-key operation is the defining feature of the Fibonacci heap. If a node's key is decreased and the new key still satisfies the heap property, no structural changes are needed. However, if the new key violates the heap property, meaning it is smaller than its parent's key, the node is cut from its parent. The cut node is moved to the root list, and its parent's degree is decremented. To prevent trees from becoming too flat, which would degrade the $O(\log n)$ bound on the maximum degree, a mechanism called cascading cuts is employed.

Cascading Cuts and the Fibonacci Sequence

To guarantee that extract-min runs in $O(\log n)$ time, the maximum degree of any node in an $n$-node Fibonacci heap must be bounded by $O(\log n)$. This requires the size of any subtree to grow exponentially with its degree. If nodes were cut from trees arbitrarily without any structural enforcement, a tree of degree $k$ could be reduced to a chain of $k$ nodes, destroying the exponential size bound and causing extract-min to take $O(n)$ time.

The cascading cut mechanism enforces the required density. Each node has a boolean mark bit, which indicates whether the node has lost a child since the last time it was made the child of another node. The mark bit essentially acts as a warning system. When a node is newly created or made a child of another node during consolidation, it starts with a clean slate and is unmarked. When a node is cut from its parent during a decrease-key operation, the parent's mark bit is checked. If the parent is unmarked, it is marked, indicating it has now lost one child and is one step away from violating the structural density requirements. If the parent is already marked, it means it has just lost its second child. In this case, the parent is also cut from its parent and moved to the root list to prevent its subtree from becoming too sparse. Once in the root list, it is no longer a child, so its mark bit is cleared. This process cascades upward until it reaches either a root node or an unmarked node.

function Decrease-Key(H, x, k)
    if k > x.key
        error "new key is greater than current key"
    x.key = k
    y = x.parent
    if y != null and x.key < y.key
        Cut(H, x, y)
        Cascading-Cut(H, y)
    if x.key < H.min.key
        H.min = x

function Cut(H, x, y)
    remove x from the child list of y
    decrement y.degree
    add x to the root list of H
    x.parent = null
    x.mark = false

function Cascading-Cut(H, y)
    z = y.parent
    if z != null
        if y.mark == false
            y.mark = true
        else
            Cut(H, y, z)
            Cascading-Cut(H, z)

Because a node is allowed to lose at most one child before being cut, the trees remain sufficiently dense. The mathematical proof of this density relies on the Fibonacci sequence. Let $s_k$ be the minimum possible number of nodes in a subtree rooted at a node of degree $k$ in a Fibonacci heap. The root node has at least $k$ children. When these children were originally attached during various consolidation phases, the root had degrees $0, 1, 2, \dots, k-1$. Therefore, the children originally had degrees $0, 1, 2, \dots, k-1$. Because a child can lose at most one of its own children after being attached, the $i$-th child currently has a degree of at least $i-2$.

Therefore, the minimum number of nodes in the subtree follows the recurrence $s_k \ge 2 + \sum_{i=2}^{k} s_{i-2}$, with base cases $s_0 = 1$ and $s_1 = 2$. This recurrence is intimately linked to the Fibonacci sequence. By substituting the Fibonacci numbers $F_0 = 0, F_1 = 1, F_2 = 1, F_3 = 2, \dots$, one can prove by induction that $s_k \ge F_{k+2}$ Wolfram MathWorld[6].

Since Fibonacci numbers grow exponentially according to the golden ratio $\phi = (1 + \sqrt{5}) / 2 \approx 1.618$, the number of nodes $n$ in a subtree of degree $k$ satisfies $n \ge \phi^k$. Taking the base-$\phi$ logarithm of both sides yields $k \le \log_{\phi} n$. Consequently, the maximum degree of any node in an $n$-node Fibonacci heap is strictly bounded by $O(\log n)$. This elegant mathematical property is the reason Fredman and Tarjan named the data structure the Fibonacci heap.

Amortized Analysis

The performance guarantees of the Fibonacci heap are proven using the potential method of amortized analysis, a technique formalized by Tarjan Tarjan, 1985[7]. The potential method assigns a real number to the state of the data structure, representing stored energy or potential that can be used to pay for expensive operations later. This can be conceptualized as a bank account. Cheap operations deposit time into the account, and expensive operations withdraw time to pay for their execution. The amortized cost of an operation is defined as its actual cost plus the change in potential it causes.

The potential of a Fibonacci heap $H$ is defined by the function $\Phi(H) = t(H) + 2m(H)$, where $t(H)$ is the number of trees in the root list, and $m(H)$ is the number of marked nodes in the heap. The constant $2$ is chosen specifically to offset the cost of cascading cuts.

When an insert operation occurs, a new tree is added to the root list. The actual cost is $O(1)$, and $t(H)$ increases by 1. The change in potential is $+1$, so the amortized cost is $O(1) + 1 = O(1)$.

The union operation simply concatenates two root lists. The actual cost is $O(1)$. The potential of the new heap is the sum of the potentials of the two original heaps, so the change in potential is zero. Thus, the amortized cost remains $O(1)$.

The find-min operation only reads a pointer. It does not modify the structure, so the change in potential is zero, and the amortized cost is $O(1)$.

During an extract-min operation, the actual cost is proportional to the number of children of the minimum node plus the number of trees in the root list, which is $O(D(n) + t(H))$. The consolidation step merges trees until no two roots have the same degree, leaving at most $D(n) + 1$ trees in the root list. The new potential is at most $D(n) + 1 + 2m(H)$. The change in potential is therefore $(D(n) + 1 + 2m(H)) - (t(H) + 2m(H)) = D(n) + 1 - t(H)$. The amortized cost is the actual cost plus the change in potential, which simplifies to $O(D(n)) = O(\log n)$. The large actual cost of traversing the root list is perfectly paid for by the massive drop in potential caused by reducing $t(H)$.

During a decrease-key operation, a cascading cut of length $c$ takes $O(c)$ actual time.[31] This process moves $c$ nodes to the root list, increasing $t(H)$ by $c$. However, it also unmarks $c - 1$ nodes (the cascading nodes) and potentially marks one node (the final parent). Therefore, $m(H)$ decreases by at least $c - 2$. The net change in potential is $\Delta \Phi \le c + 2(-(c - 2)) = c - 2c + 4 = 4 - c$. The amortized cost is the actual cost $O(c)$ plus the change in potential $4 - c$, which evaluates to a constant $O(1)$. The stored potential in the marked nodes pays for the cascading cuts, ensuring the amortized cost remains constant regardless of how many nodes are cut.

Discovery and History

The Fibonacci heap was invented by Michael L. Fredman and Robert E. Tarjan in 1984. It was first presented at the 25th Annual Symposium on Foundations of Computer Science Fredman and Tarjan, 1984[8] and subsequently formally published in the Journal of the Association for Computing Machinery in 1987 Fredman and Tarjan, 1987[2]. The invention was a direct response to a long-standing bottleneck in combinatorial optimization.

In 1959, Edsger W. Dijkstra published his algorithm for the shortest path problem. Dijkstra's original formulation used a simple array to track distances, resulting in a time complexity of $O(V^2)$. For dense graphs, this was highly efficient, but for sparse graphs, it was slow. When implemented with a standard binary heap, which was formalized by J. W. J. Williams in 1964 Williams, 1964[9], the algorithm required $O(E \log V)$ time. In 1978, Jean Vuillemin introduced binomial queues, which supported efficient merging but did not improve the $O(\log V)$ bound for decrease-key Vuillemin, 1978[5]. Michael Fredman had previously explored bounds on shortest path problems in 1976 Fredman, 1976[10], but the $O(E \log V)$ barrier remained unbroken for general graphs.

Fredman and Tarjan realized that Dijkstra's algorithm performs far more decrease-key operations than extract-min operations. They designed the Fibonacci heap specifically to optimize the amortized cost of decrease-key. The resulting $O(E + V \log V)$ bound for Dijkstra's algorithm and Prim's algorithm was a major theoretical milestone. It also improved the bounds for other network optimization algorithms, including the all-pairs shortest path problem and various maximum flow algorithms.

The impact extended rapidly to other domains. Harold Gabow, Zvi Galil, Thomas Spencer, and Tarjan utilized the Fibonacci heap to develop highly efficient algorithms for minimum spanning trees in both undirected and directed graphs Gabow et al., 1986[11], improving upon the earlier bounds established by Joseph Kruskal Kruskal, 1956[12].

Tarjan's contributions to the field of data structures and graph algorithms, including the co-invention of the Fibonacci heap, were instrumental in his receipt of the Turing Award in 1986, which he shared with John Hopcroft Tarjan Turing Award[13]. The Turing Award citation specifically highlighted their fundamental achievements in the design and analysis of algorithms and data structures. The Fibonacci heap stands as a prime example of Tarjan's broader philosophy of algorithm design, which frequently employed amortized analysis to prove that seemingly unbalanced or lazy structures could achieve optimal performance over a sequence of operations.

Important Variants

The theoretical success of the Fibonacci heap sparked a massive wave of research into priority queues, leading to several notable variants designed to simplify the structure, improve worst-case bounds, or reduce constant factors.

Pairing Heaps

In 1986, before the Fibonacci heap paper was even formally published, Fredman, Robert Sedgewick, Daniel Sleator, and Tarjan introduced the pairing heap Fredman et al., 1986[14]. The pairing heap is a self-adjusting structure that is significantly simpler to implement than the Fibonacci heap, as it requires no mark bits and uses a single tree rather than a forest. While it performs exceptionally well in practice, its theoretical bounds are slightly weaker. The decrease-key operation takes $O(2^{2\sqrt{\log \log n}})$ amortized time (with a lower bound of $\Omega(\log \log n)$), though this bound was notoriously difficult to prove and required decades of subsequent analysis.

Relaxed Heaps and Rank-Pairing Heaps

In 1988, James Driscoll, Harold Gabow, Ruth Shrairman, and Tarjan introduced relaxed heaps Driscoll et al., 1988[15]. Relaxed heaps achieve the same amortized bounds as Fibonacci heaps but relax the strict structural invariants to allow for better parallelization and to avoid the cascading cut mechanism. In 2011, Bernhard Haeupler, Siddhartha Sen, and Tarjan developed rank-pairing heaps Haeupler et al., 2011[16]. Rank-pairing heaps combine the structural simplicity of pairing heaps with the $O(1)$ amortized decrease-key bound of Fibonacci heaps by maintaining rank information instead of relying on complex tree restructuring.

Strict Fibonacci Heaps

A major theoretical criticism of the Fibonacci heap is that its $O(1)$ bounds are amortized, meaning a single decrease-key or insert operation could take $O(n)$ time in the worst case, even if the average over a sequence of operations is constant. In 1996, Gerth Stølting Brodal introduced the first priority queue to achieve the Fibonacci heap's bounds in the worst case Brodal, 1996[17]. This structure was highly complex and strictly theoretical. In 2012, Brodal, George Lagogiannis, and Tarjan refined this into the strict Fibonacci heap Brodal et al., 2012[18], which simplified the worst-case $O(1)$ implementation, though it remains too complex for practical deployment.

Violation Heaps and Quake Heaps

In 2010, Amr Elmasry introduced the violation heap, which replaces cascading cuts with a different invariant to achieve the same bounds Elmasry, 2010[19]. In 2013, Timothy Chan introduced the quake heap Chan, 2013[20]. Quake heaps use a tournament tree structure where nodes are linked based on tournament outcomes. The structure maintains a count of nodes at each height level. If the number of nodes at a specific level drops below a constant fraction of the nodes at the level below it, a global rebuilding event, termed a quake, is triggered. During a quake, all nodes above the violating level are removed, and their subtrees are dismantled and moved to the root list. This ensures the trees remain balanced without relying on cascading cuts or mark bits, simplifying the amortized analysis.

Hollow Heaps

In 2015, Thomas Dueholm Hansen, Haim Kaplan, Tarjan, and Uri Zwick introduced the hollow heap Hansen et al., 2015[21], formally published in 2017 Hansen et al., 2017[22]. Instead of moving nodes around when keys are decreased, the hollow heap uses lazy deletion. A decrease-key operation simply inserts a new node with the updated key and marks the old node as hollow or empty. The structure is represented as a directed acyclic graph rather than a forest of trees. Hollow heaps achieve the same amortized bounds as Fibonacci heaps but are considerably simpler to implement and reason about. A comprehensive review of these variants was published by Kaplan, Tarjan, and Zwick in 2014 Kaplan et al., 2014[23].

Real-World Applications

While the Fibonacci heap is a staple of computer science curricula and theoretical algorithm analysis, its adoption in production software is highly limited. The primary issue is the constant-factor overhead. Each node in a Fibonacci heap requires four pointers (parent, child, left sibling, right sibling), plus an integer for the degree, a boolean for the mark bit, and the actual key-value data. This results in high memory consumption and poor cache locality, as nodes are scattered across the heap memory.

Modern computer architectures utilize a memory hierarchy consisting of fast, small CPU caches and large, slow main memory. When a program accesses data, the CPU loads a contiguous block of memory, known as a cache line, into the fast cache. If the program subsequently accesses data within that same cache line, a cache hit occurs, and the data is retrieved almost instantly. If the program accesses data outside the cache line, a cache miss occurs, forcing the CPU to wait while data is fetched from main memory. Binary heaps, which are typically implemented using flat arrays, exhibit excellent cache locality.[32] Traversing from a parent to a child involves simple arithmetic on array indices, and the data is often already in the cache. In contrast, Fibonacci heaps allocate nodes dynamically. Traversing from a parent to a child or from one sibling to another involves dereferencing pointers to memory addresses that are likely scattered randomly across RAM. This pointer chasing behavior results in frequent cache misses, causing the CPU to stall.

However, the data structure is provided in several comprehensive algorithmic libraries:

  • Boost Graph Library (BGL): The C++ Boost Graph Library includes an implementation of Dijkstra's algorithm that can be configured to use a Fibonacci heap Boost Graph Library[24]. However, the library's documentation and empirical tests often recommend using a standard binary heap or a $d$-ary heap for real-world graphs, as they tend to execute faster in practice.
  • JGraphT: The popular Java graph library JGraphT includes a FibonacciHeap class JGraphT FibonacciHeap. It is utilized internally by several algorithms, including PrimMinimumSpanningTree, to guarantee the theoretical $O(E + V \log V)$ time complexity JGraphT PrimMinimumSpanningTree[25].

In contrast, performance-critical systems generally avoid it. The Linux kernel, which requires highly deterministic and memory-efficient data structures for task scheduling and memory management, relies on red-black trees and standard binary heaps rather than Fibonacci heaps Linux Kernel RB-Trees[26].

Empirical studies have repeatedly confirmed these practical limitations. A 2014 back-to-basics analysis by Daniel Larkin, Siddhartha Sen, and Tarjan demonstrated that standard 4-ary heaps or pairing heaps outperform Fibonacci heaps on almost all practical workloads Larkin et al., 2014[27]. The study concluded that the cache misses incurred by traversing Fibonacci heap pointers outweigh the theoretical savings in operation counts, rendering the structure suboptimal for standard computing environments.

Significance and Tradeoffs

The Fibonacci heap is one of the most important data structures in theoretical computer science. It proved that the $O(E \log V)$ barrier for shortest path problems was not absolute, fundamentally altering the trajectory of graph algorithm research. The data structure is a masterclass in amortized analysis and lazy evaluation, demonstrating how deferring work can lead to strict asymptotic improvements.

The primary tradeoff is theoretical optimality versus practical efficiency. The asymptotic bounds of the Fibonacci heap only dominate simpler structures when the number of elements $n$ is astronomically large, or when the graph is extremely dense. For sparse graphs, which are the most common type encountered in real-world networks, the $O(\log V)$ cost of a binary heap decrease-key operation is small enough that the constant-factor overhead of the Fibonacci heap makes it slower. Furthermore, the complex pointer manipulation makes the Fibonacci heap difficult to implement correctly and impossible to optimize for modern CPU caches.

Despite its lack of practical dominance, the Fibonacci heap remains an essential reference point. Any new priority queue or shortest-path algorithm is inevitably compared against the $O(E + V \log V)$ benchmark established by Fredman and Tarjan in 1984. The structure's elegant mathematical foundation and its role in popularizing amortized analysis ensure its continued relevance in the study of algorithms.

Sources (32)
  1. Dijkstra, 1959
  2. ACM Digital Library
  3. mitpress.mit.edu: Cormen et al., Introduction to Algorithms
  4. ACM Digital Library
  5. ACM Digital Library
  6. Wolfram MathWorld
  7. ACM Digital Library
  8. IEEE
  9. ACM Digital Library
  10. ACM Digital Library
  11. Gabow et al., 1986
  12. Kruskal, 1956
  13. Tarjan Turing Award
  14. ACM Digital Library
  15. ACM Digital Library
  16. Haeupler et al., 2011
  17. ACM Digital Library
  18. ACM Digital Library
  19. Elmasry, 2010
  20. ACM Digital Library
  21. Hansen et al., 2015
  22. ACM Digital Library
  23. Kaplan et al., 2014
  24. Boost Graph Library
  25. JGraphT PrimMinimumSpanningTree
  26. The Linux Kernel Archives
  27. Larkin et al., 2014
  28. Peter Sanders, Kurt Mehlhorn, Martin Dietzfelbinger, Sequential and Parallel Algorithms and Data Structures (Springer Nature, 2019)
  29. Donald Ervin Knuth, The Stanford GraphBase (Addison-Wesley Professional, 1993)
  30. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Introduction to Algorithms (MIT Press, 2009)
  31. Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Introduction to Algorithms, third edition (MIT Press, 2009)
  32. Jarkko Hietaniemi, John Macdonald, Jon Orwant, Mastering Algorithms with Perl ("O'Reilly Media, Inc.", 1999)

Recommended reading