# knotkit/heap

> Binary and k-ary min/max heaps plus indexed priority queues, ordered by comparator you supply.

Four structures in one module: a binary heap, a k-ary heap, and an indexed priority queue over each. The first two hold values and answer “what is the best remaining item”. The priority queues hold keyed entries and answer it when a resident entry’s key changes, which is the case Dijkstra, Prim, and A\* are built on.

time O(n) build, O(log n) push/pop, O(1) peek · space O(n), or O(n) plus a position index · Floyd's bottom-up heapify; updateKey is O(log n) through the index, never a search

The distinction that matters: a heap cannot find an entry it is holding, so re-keying one costs a linear search and a remove. An indexed priority queue keeps a position index, so `updateKey(key, value)` sifts in place. That is an algorithmic-class difference, and it is why the measured key-update comparison is **272× faster than `heap-js` linear remove plus push**.

## Use

```ts
import { minBinaryHeap, minPriorityQueue, numberOrder } from 'knotkit/heap'

const heap = minBinaryHeap(numberOrder, [5, 8, 3])
heap.pop() // 3

const largest = minBinaryHeap(numberOrder, [5, 8, 3])
if (7 > largest.peek()) {
  largest.replaceRoot(7) // returns 3; a fixed-size top-k
}

const queue = minPriorityQueue(numberOrder, [
  [5, 'render'],
  [1, 'parse'],
  [3, 'layout'],
])
queue.updateKey(0, 'layout') // sifts in place, no search
queue.peek() // 'layout'
```

To keep the three largest values, hold a **min** heap and admit only values that beat its root: an inverted order is what makes an eviction structure out of a priority structure.

## Which layout, and why

The `kind` table on this page carries the predicates; the short version is the operation mix.

| If the workload is…                              | Choose                                  | Because                                                            |
| ------------------------------------------------ | --------------------------------------- | ------------------------------------------------------------------ |
| pops at least as frequent as pushes, values only | `minBinaryHeap` / `maxBinaryHeap`       | fewest comparisons per sift level at the same depth                |
| pushes far outnumber pops, values only           | `minKHeap` / `maxKHeap` with `k = 4`    | a flatter tree pays `k` comparisons over fewer levels              |
| resident values are re-keyed                     | `minPriorityQueue` / `maxPriorityQueue` | O(1) lookup and an in-place sift; a heap cannot find its own entry |
| keys are dense integers and re-keying dominates  | `denseIntegerMinPriorityQueue`          | no value-to-index registry at all                                  |

Every layout, with the rule for choosing it:

| Factory                                                               | Choose when                                                                                                                           | Cost                                                                                                |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `minBinaryHeap`kind `binary-min`                                      | the caller only pushes and pops values rather than re-keying residents, and the pop count is at least the push count                  | 2 comparisons per sift-down level, ceil(log2 n) levels                                              |
| `maxBinaryHeap`kind `binary-max`                                      | the caller needs the largest value first and only pushes and pops values                                                              | 2 comparisons per sift-down level, ceil(log2 n) levels                                              |
| `minKHeap`kind `k-min`                                                | pushes outnumber pops and n is at or above 10,000, where fewer sift-up levels repay the k comparisons per level                       | k comparisons per sift level, log_k n levels                                                        |
| `maxKHeap`kind `k-max`                                                | pushes outnumber pops, n is at or above 10,000, and the caller needs the largest value first                                          | k comparisons per sift level, log_k n levels                                                        |
| `minPriorityQueue`kind `binary-priority-queue-min`                    | resident values require in-place re-keying, the dense numeric domain is unavailable, and pop count is at least the decrease-key count | 2 comparisons per sift level plus one Map lookup per key read                                       |
| `maxPriorityQueue`kind `binary-priority-queue-max`                    | resident values must be re-keyed in place and the caller needs the largest key first                                                  | 2 comparisons per sift level plus one Map lookup per key read                                       |
| `minKPriorityQueue`kind `k-priority-queue-min`                        | decrease-key calls outnumber pops and n is at or above 10,000                                                                         | k comparisons per sift level, log_k n levels, plus one Map lookup per key read                      |
| `maxKPriorityQueue`kind `k-priority-queue-max`                        | decrease-key calls outnumber pops, n is at or above 10,000, and the caller needs the largest key first                                | k comparisons per sift level, log_k n levels, plus one Map lookup per key read                      |
| `denseIntegerMinPriorityQueue`kind `dense-integer-priority-queue-min` | numeric keys require resident decrease-key and values index a known fixed dense integer domain                                        | O(capacity) space with constant-time direct position lookup and two comparisons per sift-down level |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/heap/README.md#performance)

A wider arity is a trade, not an upgrade: it makes each level more expensive and each path shorter.

## Count the comparisons

Drag the arity and the heap size: every change reruns the module’s own demo against `knotkit/heap` in your browser, counting comparator calls by wrapping the `Order` the heap takes as a parameter. The defaults reproduce the README figure.

Largest heap2,04811Children per node44Reset

* On 2,048 seeded keys, drain comparisons per pop are 9.7 / 14.9 for 2 / 4 children.
* Indexed updates move item 2047 to priority -2048 without inserting a second entry.
* The plots count comparator calls after construction.

Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/heap/demo.ts) against `knotkit/heap` in your browser; the defaults reproduce the README figure.

A wider heap pays more comparisons per pop and fewer per decrease. The right arity follows your workload’s mix of the two, which is why the module states it as a rule rather than a default.

## Save and restore

Heaps persist through a second entrypoint, `knotkit/heap/wire`, which is where the parser lives; importing `knotkit/heap` never loads it. Both binary and JSON formats are versioned, and a decoded structure is checked against the heap invariant rather than trusted — a truncated artifact fails with a code (`MISSING_NODES`, `HEAP_INVARIANT_VIOLATION`) instead of producing a heap that quietly lies about its order.

## API

| Export                                                                                            | Returns                     | Does                                                                                             |
| ------------------------------------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------ |
| [`minBinaryHeap`](/reference/knotkit/heap/functions/minbinaryheap/)                               | `BinaryHeap<A>`             | Binary min heap over any order; O(n) Floyd build from an iterable.                               |
| [`maxBinaryHeap`](/reference/knotkit/heap/functions/maxbinaryheap/)                               | `BinaryHeap<A>`             | Binary max heap over any order; O(n) Floyd build from an iterable.                               |
| [`minKHeap`](/reference/knotkit/heap/functions/minkheap/)                                         | `KHeap<A>`                  | k-ary min heap; \`k\` is the arity and is taken first.                                           |
| [`maxKHeap`](/reference/knotkit/heap/functions/maxkheap/)                                         | `KHeap<A>`                  | k-ary max heap; \`k\` is the arity and is taken first.                                           |
| [`minPriorityQueue`](/reference/knotkit/heap/functions/minpriorityqueue/)                         | `BinaryPriorityQueue<K, V>` | Indexed binary min queue: unique values, O(1) key lookup, in-place decrease-key.                 |
| [`maxPriorityQueue`](/reference/knotkit/heap/functions/maxpriorityqueue/)                         | `BinaryPriorityQueue<K, V>` | Indexed binary max queue: unique values, O(1) key lookup, in-place decrease-key.                 |
| [`minKPriorityQueue`](/reference/knotkit/heap/functions/minkpriorityqueue/)                       | `KPriorityQueue<K, V>`      | Indexed k-ary min queue; \`k\` is the arity and is taken first.                                  |
| [`maxKPriorityQueue`](/reference/knotkit/heap/functions/maxkpriorityqueue/)                       | `KPriorityQueue<K, V>`      | Indexed k-ary max queue; \`k\` is the arity and is taken first.                                  |
| [`makeOrder`](/reference/knotkit/heap/functions/makeorder/)                                       | `Order<A>`                  | Build an order from a \`(a, b) => number\` comparator, short-circuiting on referential equality. |
| [`reverseOrder`](/reference/knotkit/heap/functions/reverseorder/)                                 | `Order<A>`                  | Flip an order's direction, turning a min-comparator into a max-comparator.                       |
| [`mapInputOrder`](/reference/knotkit/heap/functions/mapinputorder/)                               | `Order<B>`                  | Derive an order on \`B\` by projecting each value to an \`A\` first.                             |
| [`denseIntegerMinPriorityQueue`](/reference/knotkit/heap/functions/denseintegerminpriorityqueue/) | `DenseIntegerPriorityQueue` | Preallocate a known dense integer domain for a numeric min queue with direct-index decrease-key. |

Cost per member. Open a row for every operation.

`minBinaryHeap` 8 members

| Member              | Cost     |
| ------------------- | -------- |
| `peek`              | O(1)     |
| `pop`               | O(log n) |
| `replaceRoot`       | O(log n) |
| `push`              | O(log n) |
| `size`              | O(1)     |
| `clear`             | O(1)     |
| `values`            | O(n)     |
| `[Symbol.iterator]` | O(n)     |

`maxBinaryHeap` 8 members

| Member              | Cost     |
| ------------------- | -------- |
| `peek`              | O(1)     |
| `pop`               | O(log n) |
| `replaceRoot`       | O(log n) |
| `push`              | O(log n) |
| `size`              | O(1)     |
| `clear`             | O(1)     |
| `values`            | O(n)     |
| `[Symbol.iterator]` | O(n)     |

`minKHeap` 8 members

| Member              | Cost         |
| ------------------- | ------------ |
| `peek`              | O(1)         |
| `pop`               | O(k log_k n) |
| `replaceRoot`       | O(k log_k n) |
| `push`              | O(log_k n)   |
| `size`              | O(1)         |
| `clear`             | O(1)         |
| `values`            | O(n)         |
| `[Symbol.iterator]` | O(n)         |

`maxKHeap` 8 members

| Member              | Cost         |
| ------------------- | ------------ |
| `peek`              | O(1)         |
| `pop`               | O(k log_k n) |
| `replaceRoot`       | O(k log_k n) |
| `push`              | O(log_k n)   |
| `size`              | O(1)         |
| `clear`             | O(1)         |
| `values`            | O(n)         |
| `[Symbol.iterator]` | O(n)         |

`minPriorityQueue` 8 members

| Member              | Cost         |
| ------------------- | ------------ |
| `peek`              | O(1)         |
| `pop`               | O(log n)     |
| `push`              | O(log n)     |
| `updateKey`         | O(log n)     |
| `keyOf`             | O(1) average |
| `clear`             | O(n)         |
| `entries`           | O(n)         |
| `[Symbol.iterator]` | O(n)         |

`maxPriorityQueue` 8 members

| Member              | Cost         |
| ------------------- | ------------ |
| `peek`              | O(1)         |
| `pop`               | O(log n)     |
| `push`              | O(log n)     |
| `updateKey`         | O(log n)     |
| `keyOf`             | O(1) average |
| `clear`             | O(n)         |
| `entries`           | O(n)         |
| `[Symbol.iterator]` | O(n)         |

`minKPriorityQueue` 8 members

| Member              | Cost         |
| ------------------- | ------------ |
| `peek`              | O(1)         |
| `pop`               | O(k log_k n) |
| `push`              | O(log_k n)   |
| `updateKey`         | O(k log_k n) |
| `keyOf`             | O(1) average |
| `clear`             | O(n)         |
| `entries`           | O(n)         |
| `[Symbol.iterator]` | O(n)         |

`maxKPriorityQueue` 8 members

| Member              | Cost         |
| ------------------- | ------------ |
| `peek`              | O(1)         |
| `pop`               | O(k log_k n) |
| `push`              | O(log_k n)   |
| `updateKey`         | O(k log_k n) |
| `keyOf`             | O(1) average |
| `clear`             | O(n)         |
| `entries`           | O(n)         |
| `[Symbol.iterator]` | O(n)         |

`denseIntegerMinPriorityQueue` 14 members

| Member              | Cost                  |
| ------------------- | --------------------- |
| `construction`      | O(capacity + entries) |
| `capacity`          | O(1)                  |
| `size`              | O(1)                  |
| `has`               | O(1)                  |
| `keyOf`             | O(1)                  |
| `peek`              | O(1)                  |
| `peekEntry`         | O(1)                  |
| `push`              | O(log n)              |
| `pop`               | O(log n)              |
| `popEntry`          | O(log n)              |
| `updateKey`         | O(log n)              |
| `clear`             | O(n)                  |
| `entries`           | O(n)                  |
| `[Symbol.iterator]` | O(n)                  |

## Errors

Every error this module throws is `HeapInvalidInputError` or `HeapParseError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `HeapInvalidInputError`

  `EMPTY` `INVALID_ARITY` `INVALID_CAPACITY` `DUPLICATE_VALUE` `INVALID_VALUE`

* `HeapParseError`

  `VALUE_NOT_FOUND` `FOREIGN_STRUCTURE` `MISSING_ELEMENT_CODEC` `INVALID_CODEC_RESULT` `NON_INJECTIVE_CODEC` `SERIALIZATION_LIMIT_EXCEEDED` `INVALID_SHAPE` `UNSUPPORTED_SCHEMA_VERSION` `UNKNOWN_KIND` `MISSING_NODES` `MISSING_ENTRIES` `HEAP_INVARIANT_VIOLATION` `INVALID_ELEMENT` `INVALID_KEY` `INVALID_MAGIC` `UNSUPPORTED_ENVELOPE_VERSION` `UNSUPPORTED_PAYLOAD_VERSION` `INVALID_SECTION_GEOMETRY` `NONZERO_PADDING` `MISALIGNED_SECTION` `TRUNCATED_PAYLOAD` `DECODE_BUDGET_EXCEEDED` `UNSTABLE_BUFFER` `WRONG_FORMAT` `INTEGRITY_MISMATCH` `INVALID_PACKAGE_HEADER`

## When not to use it

| If you need to…                                                                                   | Use instead                                                                     |
| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| sort a fixed array once                                                                           | Array.prototype.sort with a comparator                                          |
| an exact set or map, with no ordering                                                             | Set, Map                                                                        |
| remove an arbitrary resident entry, or cancel a queued task                                       | a Map plus a heap of stale entries re-checked on pop; delete is not implemented |
| track which elements are connected, and merge groups                                              | [`knotkit/disjoint-set`](/modules/disjoint-set/)                                |
| count distinct values or estimate frequencies in bounded memory                                   | [`knotkit/scalar-sketch`](/modules/scalar-sketch/)                              |
| decrease-key when values are sparse or arbitrary, or the dense integer domain capacity is unknown | minPriorityQueue (binary-priority-queue-min) from knotkit/heap                  |

## Prompt an agent

Prompt · knotkit/heapCopy prompt

```
Use knotkit/heap for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/heap'.

Exports:
- `minBinaryHeap` → `BinaryHeap<A>`: Binary min heap over any order; O(n) Floyd build from an iterable.
- `maxBinaryHeap` → `BinaryHeap<A>`: Binary max heap over any order; O(n) Floyd build from an iterable.
- `minKHeap` → `KHeap<A>`: k-ary min heap; `k` is the arity and is taken first.
- `maxKHeap` → `KHeap<A>`: k-ary max heap; `k` is the arity and is taken first.
- `minPriorityQueue` → `BinaryPriorityQueue<K, V>`: Indexed binary min queue: unique values, O(1) key lookup, in-place decrease-key.
- `maxPriorityQueue` → `BinaryPriorityQueue<K, V>`: Indexed binary max queue: unique values, O(1) key lookup, in-place decrease-key.
- `minKPriorityQueue` → `KPriorityQueue<K, V>`: Indexed k-ary min queue; `k` is the arity and is taken first.
- `maxKPriorityQueue` → `KPriorityQueue<K, V>`: Indexed k-ary max queue; `k` is the arity and is taken first.
- `makeOrder` → `Order<A>`: Build an order from a `(a, b) => number` comparator, short-circuiting on referential equality.
- `reverseOrder` → `Order<A>`: Flip an order's direction, turning a min-comparator into a max-comparator.
- `mapInputOrder` → `Order<B>`: Derive an order on `B` by projecting each value to an `A` first.
- `denseIntegerMinPriorityQueue` → `DenseIntegerPriorityQueue`: Preallocate a known dense integer domain for a numeric min queue with direct-index decrease-key.

Pick the layout by these rules:
- `minBinaryHeap` (kind 'binary-min') when the caller only pushes and pops values rather than re-keying residents, and the pop count is at least the push count
- `maxBinaryHeap` (kind 'binary-max') when the caller needs the largest value first and only pushes and pops values
- `minKHeap` (kind 'k-min') when pushes outnumber pops and n is at or above 10,000, where fewer sift-up levels repay the k comparisons per level
- `maxKHeap` (kind 'k-max') when pushes outnumber pops, n is at or above 10,000, and the caller needs the largest value first
- `minPriorityQueue` (kind 'binary-priority-queue-min') when resident values require in-place re-keying, the dense numeric domain is unavailable, and pop count is at least the decrease-key count
- `maxPriorityQueue` (kind 'binary-priority-queue-max') when resident values must be re-keyed in place and the caller needs the largest key first
- `minKPriorityQueue` (kind 'k-priority-queue-min') when decrease-key calls outnumber pops and n is at or above 10,000
- `maxKPriorityQueue` (kind 'k-priority-queue-max') when decrease-key calls outnumber pops, n is at or above 10,000, and the caller needs the largest key first
- `denseIntegerMinPriorityQueue` (kind 'dense-integer-priority-queue-min') when numeric keys require resident decrease-key and values index a known fixed dense integer domain

Inputs and their sources:
- ordering: `Order<A>` from `knotkit/heap`
- ordering on restore, which no artifact carries: `Order<A>` from `knotkit/heap`

Use something else when:
- sort a fixed array once → Array.prototype.sort with a comparator
- an exact set or map, with no ordering → Set, Map
- remove an arbitrary resident entry, or cancel a queued task → a Map plus a heap of stale entries re-checked on pop; delete is not implemented
- track which elements are connected, and merge groups → knotkit/disjoint-set
- count distinct values or estimate frequencies in bounded memory → knotkit/scalar-sketch
- decrease-key when values are sparse or arbitrary, or the dense integer domain capacity is unknown → minPriorityQueue (binary-priority-queue-min) from knotkit/heap

Errors are HeapInvalidInputError or HeapParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/heap/wire` (serializeHeap, deserializeHeap, serializeHeapJson, deserializeHeapJson, serializePriorityQueue, deserializePriorityQueue, serializePriorityQueueJson, deserializePriorityQueueJson).

Full page: https://knotkit.jkomyno.dev/modules/heap.md
Types: node_modules/knotkit/heap/ and https://knotkit.jkomyno.dev/reference/knotkit/heap/
```

## See also

* [API reference](/reference/knotkit/heap/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/heap/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/apps/docs/src/content/docs/modules/heap.mdx)suggest a change to the source record
