Skew Heap

A skew heap is a self-adjusting form of a left-leaning (leftist) heap that attempts to maintain balance by unconditionally swapping all nodes on the merge path when merging two heaps. (The merge operation is also used when inserting and removing values.)

The idea of self-adjustment

In a leftist heap, after a merge we check the ranks of the children and, if the invariant is violated, swap them (the swap function). The skew heap goes further: it does this unconditionally. At every merge we always recursively merge the root's right subtree with the other tree, and then simply swap the left and right children without looking at any balance metric.

Through such "always swap" behavior the skew heap gradually adapts its shape to the sequence of operations. Although a single operation may in the worst case be expensive (up to O(n)), the total cost of a sequence of operations is amortized to O(log n) per operation. This is a classic example of amortized analysis and a self-regulating data structure.

Comparison with the leftist heap

Operations

As with other heaps, the public operations insert and remove are expressed through merge:

Complexity

Code

enum SkewHeap[+A]:
  import SkewHeap.*

  case Leaf
  private case Branch(min: A, left: SkewHeap[A], right: SkewHeap[A])

  lazy val isEmpty: Boolean = this match
    case Leaf => true
    case _    => false

  def insert[B >: A: Ordering](x: B): SkewHeap[B] =
    merge(apply(x), this)

  def remove[B >: A: Ordering]: Option[SkewHeap[B]] = this match
    case Branch(_, left, right) => Some(merge(left, right))
    case _                      => None

end SkewHeap

object SkewHeap:
  def empty[A]: SkewHeap[A] = Leaf

  def apply[A: Ordering](x: A): SkewHeap[A] =
    Branch(x, Leaf, Leaf)

  def merge[A: Ordering](x: SkewHeap[A], y: SkewHeap[A]): SkewHeap[A] =
    (x, y) match
      case (_, Leaf) => x
      case (Leaf, _) => y
      case (Branch(x1, l1, r1), Branch(x2, l2, r2)) =>
        if x1 < x2 then
          Branch(x1, merge(Branch(x2, l2, r2), r1), l1)
        else Branch(x2, merge(Branch(x1, l1, r1), r2), l2)

end SkewHeap

Understanding the Scala implementation

Example

val emptySkewHeap: SkewHeap[Int]     = SkewHeap.empty
val nonEmptySkewHeap: SkewHeap[Int]  = SkewHeap.empty.insert(1).insert(2)

emptySkewHeap.isEmpty       // true
nonEmptySkewHeap.isEmpty    // false

emptySkewHeap.minOption     // None
nonEmptySkewHeap.minOption  // Some(1)

nonEmptySkewHeap.remove
// Some(Branch(2,Leaf,Leaf))

The example confirms that the root is always minimal, and after removing the root the new heap is again arranged correctly.


Links: