# knotkit/interval-index

> Indexes closed intervals over a caller-supplied order and finds every interval that holds a point or overlaps a range

## Use

```ts
import { augmentedRedBlackIntervalIndex } from 'knotkit/interval-index'
import { compareBytes } from 'knotkit/key-encoding'

const key = (text: string): Uint8Array => new TextEncoder().encode(text)

// Level-0 tables, each routed by its [minKey, maxKey] fence pointers.
const tables = augmentedRedBlackIntervalIndex<Uint8Array, string>(compareBytes)
const first = tables.add(key('apple'), key('cherry'), 'sst-1')
tables.add(key('banana'), key('date'), 'sst-2')
tables.add(key('fig'), key('grape'), 'sst-3')

// A point read probes every table whose fences hold the key, oldest start first.
const probes = [...tables.atPoint(key('blueberry'))].map((entry) => entry.value) // ['sst-1', 'sst-2']

// A compaction of [cherry, fig] must read every table overlapping it; touching endpoints overlap.
const inputs = [...tables.overlapping(key('cherry'), key('fig'))].map((entry) => entry.value) // ['sst-1', 'sst-2', 'sst-3']

// Compaction retires a table by the id add returned.
tables.delete(first) // true
tables.size // 2
```

## What it solves

* find which SSTables' \[minKey, maxKey] fence pointers can hold a key on a level-0 read
* select every table in the next level whose key range overlaps a compaction input
* find every booking, lease, or time window that covers a moment or overlaps a span
* keep a set of ranges that are added and removed by id while answering overlap queries
* match ranges whose endpoints are byte strings, numbers, or any keys with a total order

## Choose a layout

| Factory                                                         | Choose when                                                                                                                             | Cost                                                                                                                                                                                                                                                                                                                    |
| --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `augmentedRedBlackIntervalIndex`kind `augmented-red-black-tree` | intervals are added and deleted dynamically (such as L0 tables arriving on flush and leaving on compaction) and n exceeds a few hundred | one tree node with three links, a color, and a subtree maximum end per entry; 4.1 ms against sorted-array's 39.5 ms for 1,000 rounds of one flush, four point reads, and a compaction every fourth round over 1,000 tables, and 1.6 to 1.7 times slower than sorted-array on static queries over 1,000 to 10,000 tables |
| `sortedArrayIntervalIndex`kind `sorted-array`                   | the interval set is built once or changes infrequently relative to queries (such as immutable LSM level manifests)                      | two array slots per entry; 0.43 ms for 1,000 point queries over 10,000 tables against 0.72 ms for augmented-red-black-tree, but every query after an out-of-order add or a deletion first pays an O(n log n) or O(n) rebuild, and a single long interval near the start can make a query scan every entry after it      |

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

## API

| Export                                                                                                          | Returns               | Does                                                                                                                                                                                |
| --------------------------------------------------------------------------------------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`augmentedRedBlackIntervalIndex`](/reference/knotkit/interval-index/functions/augmentedredblackintervalindex/) | `IntervalIndex<K, V>` | Red-black tree keyed by (start, id) with each node's subtree maximum end, maintained on every insertion, deletion, and rotation, plus a map from id to node.                        |
| [`sortedArrayIntervalIndex`](/reference/knotkit/interval-index/functions/sortedarrayintervalindex/)             | `IntervalIndex<K, V>` | One array of entries sorted by (start, id) with a parallel running maximum of end, rebuilt by the first query after an out-of-order add or a deletion, plus a map from id to entry. |

Cost per member. Open a row for every operation.

`augmentedRedBlackIntervalIndex` 10 members

| Member        | Cost                                            |
| ------------- | ----------------------------------------------- |
| `build`       | O(n log n)                                      |
| `size`        | O(1)                                            |
| `add`         | O(log n)                                        |
| `delete`      | O(log n)                                        |
| `has`         | O(1)                                            |
| `get`         | O(1)                                            |
| `atPoint`     | O(min(n, (k + 1) log n)) for k entries reported |
| `overlapping` | O(min(n, (k + 1) log n)) for k entries reported |
| `entries`     | O(n)                                            |
| `clear`       | O(1)                                            |

`sortedArrayIntervalIndex` 10 members

| Member        | Cost                                                                                                                                                                            |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `build`       | O(n log n)                                                                                                                                                                      |
| `size`        | O(1)                                                                                                                                                                            |
| `add`         | O(1) amortized; an add whose start sorts before the last stored start defers an O(n log n) rebuild to the next query                                                            |
| `delete`      | O(1) amortized, O(n) when half the entries are deleted; nonempty queries rebuild prefix maxima in O(n) after deletions alone                                                    |
| `has`         | O(1)                                                                                                                                                                            |
| `get`         | O(1)                                                                                                                                                                            |
| `atPoint`     | O(log n + m) once settled, where m counts entries from the first whose running maximum end reaches the query start to the last starting at or before the query end; k <= m <= n |
| `overlapping` | O(log n + m) once settled, where m counts entries from the first whose running maximum end reaches the query start to the last starting at or before the query end; k <= m <= n |
| `entries`     | O(n) once settled                                                                                                                                                               |
| `clear`       | O(1)                                                                                                                                                                            |

## What you pass in

| Input     | Type       | Get one from                     |
| --------- | ---------- | -------------------------------- |
| key order | `Order<K>` | [`knotkit/heap`](/modules/heap/) |

## Errors

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

* `INVALID_INTERVAL` `MODIFIED_DURING_ITERATION`

## When not to use it

| If you need to…                                                    | Use instead                                      |
| ------------------------------------------------------------------ | ------------------------------------------------ |
| look up, rank, or scan single keys rather than ranges              | [`knotkit/ordered-map`](/modules/ordered-map/)   |
| membership or range counts over unsigned 32-bit integer ids        | [`knotkit/bitset`](/modules/bitset/)             |
| a compact immutable block of sorted byte-keyed entries with seeks  | [`knotkit/sorted-block`](/modules/sorted-block/) |
| the longest stored prefix of a delimiter-separated key             | [`knotkit/trie`](/modules/trie/)                 |
| overlap queries over rectangles or boxes in two or more dimensions | an R-tree library such as rbush                  |

## Performance

Measured by the suite in [`packages/interval-index/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/interval-index/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/interval-indexCopy prompt

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

Exports:
- `augmentedRedBlackIntervalIndex` → `IntervalIndex<K, V>`: Red-black tree keyed by (start, id) with each node's subtree maximum end, maintained on every insertion, deletion, and rotation, plus a map from id to node.
- `sortedArrayIntervalIndex` → `IntervalIndex<K, V>`: One array of entries sorted by (start, id) with a parallel running maximum of end, rebuilt by the first query after an out-of-order add or a deletion, plus a map from id to entry.

Pick the layout by these rules:
- `augmentedRedBlackIntervalIndex` (kind 'augmented-red-black-tree') when intervals are added and deleted dynamically (such as L0 tables arriving on flush and leaving on compaction) and n exceeds a few hundred
- `sortedArrayIntervalIndex` (kind 'sorted-array') when the interval set is built once or changes infrequently relative to queries (such as immutable LSM level manifests)

Inputs and their sources:
- key order: `Order<K>` from `knotkit/heap`

Use something else when:
- look up, rank, or scan single keys rather than ranges → knotkit/ordered-map
- membership or range counts over unsigned 32-bit integer ids → knotkit/bitset
- a compact immutable block of sorted byte-keyed entries with seeks → knotkit/sorted-block
- the longest stored prefix of a delimiter-separated key → knotkit/trie
- overlap queries over rectangles or boxes in two or more dimensions → an R-tree library such as rbush

Errors are IntervalIndexInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

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

## See also

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