← The Ledger
Vol. I, No. 16 · Heap Structures

The Pairing Heap

One heap-ordered tree with no shape invariant, rebuilt only when the minimum leaves.

Written by Khushal Agrawal

loading…

One Heap-Ordered Tree

A pairing heap is a single tree in which every node's key is no greater than the keys of its children. There is no degree constraint, no balance rule, and no rank or mark field: a root may have one child or a thousand. The minimum is the root, so find-min is O(1) worst-case.

Shape is determined entirely by the operation history, and correctness never depends on it, so nothing is ever repaired for its own sake. Fredman, Sedgewick, Sleator, and Tarjan introduced the structure in 1986 as a self-adjusting alternative to the Fibonacci heap, with the same restructure-on-access idea as the splay tree.

The Node Record

The tree is stored in child-sibling form. Each node points to its leftmost child and to its next sibling, and one back pointer makes any node removable in constant time.

typedef struct pnode {
    key_t         key;
    struct pnode *child;   // leftmost child
    struct pnode *next;    // next sibling to the right
    struct pnode *prev;    // left sibling, or the parent if leftmost
} pnode;

Overloading prev is what keeps the record at three pointers: a leftmost child needs its parent, every other child needs its left neighbour, and no node needs both. There is no degree counter and no mark bit, so the node is roughly a third smaller than a Fibonacci heap node.

Meld

The one primitive is meld: compare the two roots and make the larger one the leftmost child of the smaller. The demoted root's subtree was already ordered, and its new parent is smaller, so the result is a valid heap.

pnode *meld(pnode *a, pnode *b) {
    if (!a) return b;
    if (!b) return a;
    if (b->key < a->key) { pnode *t = a; a = b; b = t; }
    b->prev = a;                    // b becomes a's leftmost child
    b->next = a->child;
    if (a->child) a->child->prev = b;
    a->child = b;
    return a;
}

One comparison and four pointer writes, O(1) worst-case. An array-backed binary heap needs O(n) to combine two queues and a binomial heap O(log n). Every other operation in this chapter is written in terms of this function.

Insert And Find-Min

Insertion wraps the key in a one-node heap and melds it with the root. A key larger than the root becomes its new leftmost child; a smaller key becomes the new root, with the whole old heap as its only child.

pnode *insert(pnode *root, pnode *x) {
    x->child = x->next = x->prev = NULL;
    return meld(root, x);          // O(1) worst case
}

Inserting n increasing keys leaves a root with n children, and n decreasing keys leave a path of length n. Both are legal and neither is repaired until a delete-min forces the issue. There is only ever one root, so unlike a Fibonacci heap there is no root list to consolidate later.

Two-Pass Delete-Min

Deleting the root leaves its children as a list of independent heaps. The first pass melds them in disjoint pairs from left to right; the second melds the results into one tree from right to left.

pnode *merge_pairs(pnode *first) {
    pnode *pairs = NULL;
    while (first) {                        // pass 1: left to right
        pnode *a = first, *b = a->next;
        first = b ? b->next : NULL;
        a->next = a->prev = NULL;
        if (b) { b->next = b->prev = NULL; a = meld(a, b); }
        a->next = pairs;                   // push: pairs ends up reversed
        pairs = a;
    }
    pnode *root = NULL;
    while (pairs) {                        // pass 2: right to left
        pnode *nx = pairs->next;
        pairs->next = NULL;
        root = meld(root, pairs);
        pairs = nx;
    }
    return root;
}

Melding five children takes four links: two in the pairing pass, two in the accumulation. One call can cost Θ(n) when the root has many children, but the amortized cost is O(log n), and the children that were paired now sit one level lower, so the next delete-min sees fewer of them. This pass is the only place the structure does real work.

Why Two Passes

A single left-to-right pass, melding the second child into the first, then the third into that, and so on, is simpler and also correct, but it degrades. Inserting n keys in decreasing order and then repeatedly deleting the minimum produces long paths that the one-pass rule never shortens, giving Θ(n) amortized cost per operation.

The pairing pass is what shortens them. It halves the number of trees before any accumulation, and each pairing link places two trees of similar history side by side under one root rather than stacking them into a chain. Multipass variants repeat the pairing step until one tree remains and also reach O(log n) amortized, but the two-pass version has the best constants measured in practice.

Decrease-Key

Decrease-key lowers a node's key. At the root nothing else happens. Elsewhere the node is cut from its parent's child list, taking its subtree with it, and melded with the root.

pnode *decrease_key(pnode *root, pnode *x, key_t k) {
    x->key = k;
    if (x == root) return root;
    if (x->prev->child == x) x->prev->child = x->next;  // leftmost
    else                     x->prev->next  = x->next;  // otherwise
    if (x->next) x->next->prev = x->prev;
    x->next = x->prev = NULL;
    return meld(root, x);
}

Nothing marks the parent and nothing cascades. A Fibonacci heap tracks lost children to protect its degree bound; a pairing heap has no degree bound and simply cuts. The cost of that simplicity appears in the analysis rather than in the code.

Deleting An Arbitrary Node

Removing a node that is not the root combines the two operations already defined. Detach the node with its subtree exactly as decrease-key does; the node is then the minimum of its own heap, so delete-min on it pairs its children; meld the result back into the main tree.

pnode *erase(pnode *root, pnode *x) {
    if (x == root) return merge_pairs(root->child);
    detach(x);                                  // as in decrease_key
    return meld(root, merge_pairs(x->child));
}

The cost is that of one delete-min, O(log n) amortized. This is what lets a handle-based priority queue cancel a pending entry, which an array heap can do only with a side index of positions.

The Potential Function

The original analysis reads the child-sibling links as a binary tree, with child as the left pointer and next as the right, and charges each node the logarithm of its binary subtree size.

s(x)  = nodes in x's subtree in the binary view
Phi   = sum over x of log2 s(x)

delete-min with k children:
  actual work        about k links
  change in Phi      at most -k + O(log n)   // the pairing pass pays
  amortized          O(log n)

This is the potential used for the splay tree, and amortized analysis explains the accounting. The first pass is what lowers the potential; an accumulation pass alone does not, which is the formal reason the one-pass rule fails.

Amortized Bounds

Find-min, insert, and meld are O(1) worst-case, and every operation is O(log n) amortized. Delete-min is Θ(log n) amortized, matching a binary heap asymptotically, while an individual delete-min can be linear in the number of children of the root.

The 1986 paper conjectured that pairing heaps match Fibonacci heaps on every operation, including O(1) amortized decrease-key. Fredman disproved that in 1999: any structure in the pairing-heap model needs Ω(log log n) amortized time per decrease-key. Pettie later proved an upper bound of 2^{O(√(log log n))}, between constant and logarithmic and still above the lower bound. The exact cost remains open.

The Decrease-Key Question

The gap matters for the algorithm that motivated both structures. Dijkstra's algorithm with a Fibonacci heap runs in O(m + n log n) because decrease-key is constant amortized. With a pairing heap the best proven bound is worse by the 2^{O(√(log log n))} factor, so on paper the older structure wins.

Measurements invert that. Experimental studies of priority queues under Dijkstra's algorithm consistently find pairing heaps competitive with or faster than Fibonacci heaps on real graphs, because each operation touches fewer fields and allocates less. The unresolved bound describes behaviour on adversarial sequences that shortest-path workloads do not produce.

Engineering Trade-offs

Pairing heaps are the usual choice when a workload needs cheap meld or frequent decrease-key and cannot justify a Fibonacci heap. They give O(1) worst-case insert and meld, three pointers per node, an implementation under a hundred lines, and measured performance close to the best available for graph algorithms.

They give no worst-case guarantee on delete-min or decrease-key, so a latency-bound service can still see a single linear operation. They also pay the pointer chasing of every linked heap: on workloads that only insert and extract, an array-backed binary heap remains faster. The theoretical decrease-key cost is neither constant nor fully known, which rules them out where a proven bound is part of the requirement.

Applications

The GNU C++ library's policy-based data structures use a pairing heap as the default implementation of __gnu_pbds::priority_queue: the Tag template parameter defaults to pairing_heap_tag, ahead of the binary, binomial, redundant-counter binomial, and thin heap tags. That container supplies the mutable-handle interface, so decrease-key is available where std::priority_queue offers none. Boost.Heap ships boost::heap::pairing_heap for the same purpose.

Those are implementations, not deployments. The sources reviewed for this chapter do not identify a named production system documenting a pairing heap in a specific component; the evidence that it is the practical member of the meldable family comes from experimental studies under Dijkstra's algorithm rather than from system documentation.

Summary

A pairing heap is one heap-ordered tree with no shape invariant, built from a meld that links the larger root under the smaller. Insert and meld are O(1) worst-case; delete-min combines the orphaned children in a pairing pass and an accumulation pass; decrease-key cuts a subtree and melds it at the root; arbitrary deletion is a detach, a delete-min, and a meld.

Every operation is O(log n) amortized, delete-min is Θ(log n) amortized, and the true amortized cost of decrease-key lies between Ω(log log n) and 2^{O(√(log log n))}. In exchange for that unresolved bound, the structure needs three pointers per node and a short implementation.

The Pairing Heap: One heap-ordered tree with no shape invariant, rebuilt only when the minimum leaves
The Pairing Heap — One heap-ordered tree with no shape invariant, rebuilt only when the minimum leaves.

Sources & further reading

Every claim in this chapter traces to a primary source. Peer-reviewed papers are linked by DOI.

Primary sources

  1. Fredman, M. L., Sedgewick, R., Sleator, D. D. & Tarjan, R. E. (1986). The pairing heap: a new form of self-adjusting heap. Algorithmica, 1(1), 111–129. doi.org/10.1007/BF01840439
  2. Fredman, M. L. (1999). On the efficiency of pairing heaps and related data structures. Journal of the ACM, 46(4), 473–501. doi.org/10.1145/320211.320214
  3. Iacono, J. (2000). Improved upper bounds for pairing heaps. Scandinavian Workshop on Algorithm Theory, 32–45. doi.org/10.1007/3-540-44985-X_5
  4. Pettie, S. (2005). Towards a final analysis of pairing heaps. 46th Annual IEEE Symposium on Foundations of Computer Science, 174–183. doi.org/10.1109/SFCS.2005.75

Applications and implementations

  1. GNU Project. libstdc++ Policy-Based Data Structures: __gnu_pbds::priority_queue (default Tag is pairing_heap_tag). gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/priority_queue.html
  2. Boost C++ Libraries. Boost.Heap: pairing_heap. www.boost.org/doc/libs/release/doc/html/boost/heap/pairing_heap.html
  3. Chen, M., Chowdhury, R. A., Ramachandran, V., Roche, D. L. & Tong, L. (2007). Priority Queues and Dijkstra’s Algorithm. UTCS Technical Report TR-07-54. www3.cs.stonybrook.edu/~rezaul/papers/TR-07-54.pdf
  4. Stasko, J. T. & Vitter, J. S. (1987). Pairing heaps: experiments and analysis. Communications of the ACM, 30(3), 234–249. doi.org/10.1145/214748.214759

Enjoyed this chapter? Support The Ledger.