# knotkit/disjoint-set

> Tracks which elements belong to the same set, with dense-index, object, and struct-of-arrays layouts

## Use

```ts
import { indexedDisjointSet } from 'knotkit/disjoint-set'

const components = indexedDisjointSet(4) // elements 0, 1, 2, 3

components.unite(0, 1)
components.unite(1, 2)

components.areConnected(0, 2) // true
components.areConnected(0, 3) // false
components.setCount // 2
```

```ts
import { objectDisjointSet } from 'knotkit/disjoint-set'

const network = objectDisjointSet(['a', 'b', 'c', 'd'])

network.unite('a', 'b') // true, two sets became one
network.unite('b', 'c') // true
network.unite('a', 'c') // false, they were already connected

network.areConnected('a', 'd') // false
network.sets() // Map { 'a' => ['a', 'b', 'c'], 'd' => ['d'] }
```

## What it solves

* tell whether two items are already connected, while connections keep arriving one at a time
* merge two groups of items into one, pair by pair, and count how many groups remain
* run Kruskal's minimum spanning tree, or detect a cycle in an undirected graph
* group a large collection of items into its connected components
* drive percolation, image segmentation, or any equivalence relation that only ever grows by merging

## Choose a layout

| Factory                                            | Choose when                                                                                                                                                                                                                     | Cost                                                                                                                                                         |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `indexedDisjointSet`kind `indexed`                 | every element is a dense integer in \`0..size - 1\`, or \`append\` can mint the next one, so no value-to-index registry is needed; at 100,000 elements each measured workload runs 4.2x to 138x faster than the generic layouts | 5 bytes of typed-array storage per initial element and no per-element Map entry; \`append\` grows geometrically and can reserve up to twice the current size |
| `objectDisjointSet`kind `object`                   | identifiers are arbitrary, sparse, or non-numeric, and a node object per element is worth inspecting while debugging; the object and struct-of-arrays layouts stay within the same order of magnitude at 100,000 elements       | 5 bytes of node storage plus one Map entry per element, and one heap object allocation per element                                                           |
| `structOfArraysDisjointSet`kind `struct-of-arrays` | identifiers are arbitrary, sparse, or non-numeric, n is at or above 100,000, and no per-element node object is ever read                                                                                                        | 5 bytes of node storage plus one Map entry and one array slot per element, with typed-array growth on insert                                                 |

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

## Worked example

* 10 edges: 7 connected separate components, 3 joined already-connected nodes.
* Remaining components across indexed, object, and struct-of-arrays: 1, 1, 1.

Hover or focus a chart for exact values. Drawn by [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/disjoint-set/demo.ts) against `knotkit/disjoint-set`.

## API

| Export                                                                                              | Returns                  | Does                                                                                                                                             |
| --------------------------------------------------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`indexedDisjointSet`](/reference/knotkit/disjoint-set/functions/indexeddisjointset/)               | `IndexedDisjointSet`     | Dense integer disjoint set over \`0..size - 1\`: parent and rank in typed arrays, no element-to-index registry; \`append\` mints the next index. |
| [`objectDisjointSet`](/reference/knotkit/disjoint-set/functions/objectdisjointset/)                 | `GrowableDisjointSet<T>` | Growable disjoint set over any values, keeping one \`{ parent, rank }\` object per element and a registry from value to dense index.             |
| [`structOfArraysDisjointSet`](/reference/knotkit/disjoint-set/functions/structofarraysdisjointset/) | `GrowableDisjointSet<T>` | Growable disjoint set over any values, keeping parent and rank in typed arrays behind the same value-to-index registry.                          |

Cost per member. Open a row for every operation.

`indexedDisjointSet` 9 members

| Member         | Cost                      |
| -------------- | ------------------------- |
| `size`         | O(1)                      |
| `setCount`     | O(1)                      |
| `has`          | O(1)                      |
| `unite`        | O(alpha(n)) amortized     |
| `areConnected` | O(alpha(n)) amortized     |
| `find`         | O(alpha(n)) amortized     |
| `elements`     | O(1) per step, O(n) total |
| `sets`         | O(n \* alpha(n))          |
| `append`       | O(1) amortized            |

`objectDisjointSet` 9 members

| Member         | Cost                      |
| -------------- | ------------------------- |
| `size`         | O(1)                      |
| `setCount`     | O(1)                      |
| `has`          | O(1) average              |
| `unite`        | O(alpha(n)) amortized     |
| `areConnected` | O(alpha(n)) amortized     |
| `find`         | O(alpha(n)) amortized     |
| `elements`     | O(1) per step, O(n) total |
| `sets`         | O(n \* alpha(n))          |
| `add`          | O(1) amortized            |

`structOfArraysDisjointSet` 9 members

| Member         | Cost                      |
| -------------- | ------------------------- |
| `size`         | O(1)                      |
| `setCount`     | O(1)                      |
| `has`          | O(1) average              |
| `unite`        | O(alpha(n)) amortized     |
| `areConnected` | O(alpha(n)) amortized     |
| `find`         | O(alpha(n)) amortized     |
| `elements`     | O(1) per step, O(n) total |
| `sets`         | O(n \* alpha(n))          |
| `add`          | O(1) amortized            |

## What you pass in

| Input                                                                                      | Type                             | Get one from                     |
| ------------------------------------------------------------------------------------------ | -------------------------------- | -------------------------------- |
| element encoding for a binary artifact of a generic layout, which no artifact carries back | `ElementCodec<T>`                | [`knotkit/wire`](/modules/wire/) |
| element validation for a JSON artifact, whose projections carry no element types           | `(value: unknown) => value is T` | `the caller`                     |

## Errors

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

* `DisjointSetInvalidInputError`

  `ELEMENT_ALREADY_REGISTERED` `SIZE_OUT_OF_RANGE`

* `DisjointSetParseError`

  `ELEMENT_NOT_FOUND` `MAX_SIZE_EXCEEDED` `MISSING_ELEMENT_CODEC` `INVALID_CODEC_RESULT` `NON_INJECTIVE_CODEC` `SERIALIZATION_LIMIT_EXCEEDED` `INVALID_SHAPE` `UNSUPPORTED_SCHEMA_VERSION` `UNKNOWN_KIND` `MISSING_ELEMENTS` `INVALID_LABELS` `INVALID_INDEXED_ELEMENT` `INVALID_ELEMENT` `ELEMENTS_LABELS_LENGTH_MISMATCH` `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` `DUPLICATE_ELEMENT`

## Save and restore

Serialization lives in a separate entrypoint, `knotkit/disjoint-set/wire`, so code that never saves a structure never loads a parser.

* Functions

  `serializeDisjointSet`, `deserializeDisjointSet`, `serializeDisjointSetJson`, `deserializeDisjointSetJson`

* Formats

  binary, json

* Compatibility

  schema-versioned, envelope v1

## When not to use it

| If you need to…                                                             | Use instead                                                                     |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| look up a value by key, or check whether a single value is present          | Set, Map                                                                        |
| sort edges by weight before merging them one by one                         | Array.prototype.sort with a comparator                                          |
| read membership as it was at an earlier moment while the set keeps changing | [`knotkit/snapshot-set`](/modules/snapshot-set/)                                |
| split a group apart, or undo a merge                                        | rebuild the structure from the unions you kept, because a merge is never undone |
| walk a graph's adjacency, or find the shortest path                         | [`knotkit/graph`](/modules/graph/)                                              |

## Performance

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

## Prompt an agent

Prompt · knotkit/disjoint-setCopy prompt

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

Exports:
- `indexedDisjointSet` → `IndexedDisjointSet`: Dense integer disjoint set over `0..size - 1`: parent and rank in typed arrays, no element-to-index registry; `append` mints the next index.
- `objectDisjointSet` → `GrowableDisjointSet<T>`: Growable disjoint set over any values, keeping one `{ parent, rank }` object per element and a registry from value to dense index.
- `structOfArraysDisjointSet` → `GrowableDisjointSet<T>`: Growable disjoint set over any values, keeping parent and rank in typed arrays behind the same value-to-index registry.

Pick the layout by these rules:
- `indexedDisjointSet` (kind 'indexed') when every element is a dense integer in `0..size - 1`, or `append` can mint the next one, so no value-to-index registry is needed; at 100,000 elements each measured workload runs 4.2x to 138x faster than the generic layouts
- `objectDisjointSet` (kind 'object') when identifiers are arbitrary, sparse, or non-numeric, and a node object per element is worth inspecting while debugging; the object and struct-of-arrays layouts stay within the same order of magnitude at 100,000 elements
- `structOfArraysDisjointSet` (kind 'struct-of-arrays') when identifiers are arbitrary, sparse, or non-numeric, n is at or above 100,000, and no per-element node object is ever read

Inputs and their sources:
- element encoding for a binary artifact of a generic layout, which no artifact carries back: `ElementCodec<T>` from `knotkit/wire`
- element validation for a JSON artifact, whose projections carry no element types: `(value: unknown) => value is T` from `the caller`

Use something else when:
- look up a value by key, or check whether a single value is present → Set, Map
- sort edges by weight before merging them one by one → Array.prototype.sort with a comparator
- read membership as it was at an earlier moment while the set keeps changing → knotkit/snapshot-set
- split a group apart, or undo a merge → rebuild the structure from the unions you kept, because a merge is never undone
- walk a graph's adjacency, or find the shortest path → knotkit/graph

Errors are DisjointSetInvalidInputError or DisjointSetParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/disjoint-set/wire` (serializeDisjointSet, deserializeDisjointSet, serializeDisjointSetJson, deserializeDisjointSetJson).

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

## See also

* [API reference](/reference/knotkit/disjoint-set/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/disjoint-set/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/disjoint-set/knotkit.capability.json)suggest a change to the source record
