Skip to content

knotkit/disjoint-set

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

import {
function indexedDisjointSet(size: number): IndexedDisjointSet

Create a disjoint set over the dense integer range 0..size - 1.

Parent pointers and ranks are stored directly in typed arrays, with no element-to-index Map or element array. Calling append adds and returns the next dense index.

@param ― size - Initial number of elements.

@throws ― {DisjointSetInvalidInputError} When size is not a safe integer in the supported Int32Array index range.

indexedDisjointSet
} from 'knotkit/disjoint-set'
const
const components: IndexedDisjointSet
components
=
function indexedDisjointSet(size: number): IndexedDisjointSet

Create a disjoint set over the dense integer range 0..size - 1.

Parent pointers and ranks are stored directly in typed arrays, with no element-to-index Map or element array. Calling append adds and returns the next dense index.

@param ― size - Initial number of elements.

@throws ― {DisjointSetInvalidInputError} When size is not a safe integer in the supported Int32Array index range.

indexedDisjointSet
(4) // elements 0, 1, 2, 3
const components: IndexedDisjointSet
components
.
DisjointSet<number>.unite: (x: number, y: number) => boolean

Merge the sets containing x and y. O(alpha(n)) amortized.

@returns ― true when two distinct sets were merged, false when both elements already belonged to the same set.

@throws ― {DisjointSetInvalidInputError} When either element is absent.

unite
(0, 1)
const components: IndexedDisjointSet
components
.
DisjointSet<number>.unite: (x: number, y: number) => boolean

Merge the sets containing x and y. O(alpha(n)) amortized.

@returns ― true when two distinct sets were merged, false when both elements already belonged to the same set.

@throws ― {DisjointSetInvalidInputError} When either element is absent.

unite
(1, 2)
const components: IndexedDisjointSet
components
.
DisjointSet<number>.areConnected: (x: number, y: number) => boolean

Return true when x and y belong to the same set. O(alpha(n)) amortized.

@throws ― {DisjointSetInvalidInputError} When either element is absent.

areConnected
(0, 2) // true
const components: IndexedDisjointSet
components
.
DisjointSet<number>.areConnected: (x: number, y: number) => boolean

Return true when x and y belong to the same set. O(alpha(n)) amortized.

@throws ― {DisjointSetInvalidInputError} When either element is absent.

areConnected
(0, 3) // false
const components: IndexedDisjointSet
components
.
DisjointSet<number>.setCount: number

Number of disjoint sets. O(1).

setCount
// 2
disjoint-set.ts
import {
function objectDisjointSet<T>(elements?: Iterable<T>): GrowableDisjointSet<T>

Create a

DisjointSet

backed by one { parent, rank } object per element, optionally pre-populated with elements that each start in their own singleton set.

Merges follow union by rank. The shorter tree is attached under the taller one, so tree height grows only when two trees of equal rank meet. Lookups follow path halving, a single-pass compression that repoints every node it visits to its grandparent and then continues from that grandparent. Together they bound each operation at O(alpha(n)) amortized time.

Prefer

indexedDisjointSet

when elements are the dense integer range 0..size - 1, or

structOfArraysDisjointSet

for large generic element counts.

@param ― elements - Elements to insert, each in its own singleton set.

@throws ― {DisjointSetInvalidInputError} When elements yields the same element twice.

objectDisjointSet
} from 'knotkit/disjoint-set'
const
const network: GrowableDisjointSet<string>
network
=
objectDisjointSet<string>(elements?: Iterable<string> | undefined): GrowableDisjointSet<string>

Create a

DisjointSet

backed by one { parent, rank } object per element, optionally pre-populated with elements that each start in their own singleton set.

Merges follow union by rank. The shorter tree is attached under the taller one, so tree height grows only when two trees of equal rank meet. Lookups follow path halving, a single-pass compression that repoints every node it visits to its grandparent and then continues from that grandparent. Together they bound each operation at O(alpha(n)) amortized time.

Prefer

indexedDisjointSet

when elements are the dense integer range 0..size - 1, or

structOfArraysDisjointSet

for large generic element counts.

@param ― elements - Elements to insert, each in its own singleton set.

@throws ― {DisjointSetInvalidInputError} When elements yields the same element twice.

objectDisjointSet
(['a', 'b', 'c', 'd'])
const network: GrowableDisjointSet<string>
network
.
DisjointSet<string>.unite: (x: string, y: string) => boolean

Merge the sets containing x and y. O(alpha(n)) amortized.

@returns ― true when two distinct sets were merged, false when both elements already belonged to the same set.

@throws ― {DisjointSetInvalidInputError} When either element is absent.

unite
('a', 'b') // true, two sets became one
const network: GrowableDisjointSet<string>
network
.
DisjointSet<string>.unite: (x: string, y: string) => boolean

Merge the sets containing x and y. O(alpha(n)) amortized.

@returns ― true when two distinct sets were merged, false when both elements already belonged to the same set.

@throws ― {DisjointSetInvalidInputError} When either element is absent.

unite
('b', 'c') // true
const network: GrowableDisjointSet<string>
network
.
DisjointSet<string>.unite: (x: string, y: string) => boolean

Merge the sets containing x and y. O(alpha(n)) amortized.

@returns ― true when two distinct sets were merged, false when both elements already belonged to the same set.

@throws ― {DisjointSetInvalidInputError} When either element is absent.

unite
('a', 'c') // false, they were already connected
const network: GrowableDisjointSet<string>
network
.
DisjointSet<string>.areConnected: (x: string, y: string) => boolean

Return true when x and y belong to the same set. O(alpha(n)) amortized.

@throws ― {DisjointSetInvalidInputError} When either element is absent.

areConnected
('a', 'd') // false
const network: GrowableDisjointSet<string>
network
.
DisjointSet<string>.sets: () => Map<string, string[]>

Collect every set into a Map keyed by representative. Members appear in insertion order. O(n * alpha(n)) time and O(n) space. The result is a copy and does not track later mutations.

sets
() // Map { 'a' => ['a', 'b', 'c'], 'd' => ['d'] }
  • 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
FactoryChoose whenCost
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 layouts5 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 elements5 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 read5 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

{"v":1,"box":[38.4774,94.1597,835.3333,437.3555],"x":{"s":"linear","lim":[-0.45,10.45],"inv":false,"g":0,"t":"Edges processed","tk":[[0,"0"],[2,"2"],[4,"4"],[6,"6"],[8,"8"],[10,"10"]]},"y":{"s":"linear","lim":[-0.36,8.36],"inv":false,"g":0,"tk":[[0,"0"],[2,"2"],[4,"4"],[6,"6"],[8,"8"]]},"ti":"7 of 10 edges joined components; a–c, d–g and c–e closed cycles","a":[{"k":"line","c":"#fffff8","s":"x","d":[0,8,1,7,2,6,3,6,4,5,5,4,6,3,7,3,8,2,9,2,10,1],"p":[71.38,108.33,144.48,147.69,217.59,187.04,290.69,187.04,363.8,226.4,436.91,265.76,510.01,305.11,583.12,305.11,656.22,344.47,729.33,344.47,802.44,383.83]},{"k":"line","c":"#1d5fa6","s":"x","d":[0,8,1,7,2,6,3,6,4,5,5,4,6,3,7,3,8,2,9,2,10,1],"p":[71.38,108.33,144.48,147.69,217.59,187.04,290.69,187.04,363.8,226.4,436.91,265.76,510.01,305.11,583.12,305.11,656.22,344.47,729.33,344.47,802.44,383.83]},{"k":"line","c":"#fffff8","s":"x","d":[0,0,1,1,2,2,3,2,4,3,5,4,6,5,7,5,8,6,9,6,10,7],"p":[71.38,423.19,144.48,383.83,217.59,344.47,290.69,344.47,363.8,305.11,436.91,265.76,510.01,226.4,583.12,226.4,656.22,187.04,729.33,187.04,802.44,147.69]},{"k":"line","c":"#c4501b","s":"x","d":[0,0,1,1,2,2,3,2,4,3,5,4,6,5,7,5,8,6,9,6,10,7],"p":[71.38,423.19,144.48,383.83,217.59,344.47,290.69,344.47,363.8,305.11,436.91,265.76,510.01,226.4,583.12,226.4,656.22,187.04,729.33,187.04,802.44,147.69]},{"k":"line","c":"#fffff8","s":"x","d":[0,0,1,0,2,0,3,1,4,1,5,1,6,1,7,2,8,2,9,3,10,3],"p":[71.38,423.19,144.48,423.19,217.59,423.19,290.69,383.83,363.8,383.83,436.91,383.83,510.01,383.83,583.12,344.47,656.22,344.47,729.33,305.11,802.44,305.11]},{"k":"line","c":"#0b7f61","s":"x","d":[0,0,1,0,2,0,3,1,4,1,5,1,6,1,7,2,8,2,9,3,10,3],"p":[71.38,423.19,144.48,423.19,217.59,423.19,290.69,383.83,363.8,383.83,436.91,383.83,510.01,383.83,583.12,344.47,656.22,344.47,729.33,305.11,802.44,305.11]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"},{"k":"annotation","c":"#0b7f61"}],"lg":[]} 0 2 4 6 8 10 Edges processed 0 2 4 6 8 Count after each edge Remaining components Successful unions Already connected 7 of 10 edges joined components; a–c, d–g and c–e closed cycles
{"v":1,"box":[38.4774,122.3921,387.3333,437.3555],"x":{"s":"linear","lim":[-0.45,10.45],"inv":false,"g":0,"t":"Edges processed","tk":[[0,"0"],[2,"2"],[4,"4"],[6,"6"],[8,"8"],[10,"10"]]},"y":{"s":"linear","lim":[-0.36,8.36],"inv":false,"g":0,"tk":[[0,"0"],[2,"2"],[4,"4"],[6,"6"],[8,"8"]]},"ti":"7 of 10 edges joined components; a–c, d–g\nand c–e closed cycles","a":[{"k":"line","c":"#fffff8","s":"x","d":[0,8,1,7,2,6,3,6,4,5,5,4,6,3,7,3,8,2,9,2,10,1],"p":[52.88,135.4,84.88,171.51,116.89,207.63,148.9,207.63,180.9,243.75,212.91,279.87,244.91,315.99,276.92,315.99,308.92,352.11,340.93,352.11,372.93,388.23]},{"k":"line","c":"#1d5fa6","s":"x","d":[0,8,1,7,2,6,3,6,4,5,5,4,6,3,7,3,8,2,9,2,10,1],"p":[52.88,135.4,84.88,171.51,116.89,207.63,148.9,207.63,180.9,243.75,212.91,279.87,244.91,315.99,276.92,315.99,308.92,352.11,340.93,352.11,372.93,388.23]},{"k":"line","c":"#fffff8","s":"x","d":[0,0,1,1,2,2,3,2,4,3,5,4,6,5,7,5,8,6,9,6,10,7],"p":[52.88,424.35,84.88,388.23,116.89,352.11,148.9,352.11,180.9,315.99,212.91,279.87,244.91,243.75,276.92,243.75,308.92,207.63,340.93,207.63,372.93,171.51]},{"k":"line","c":"#c4501b","s":"x","d":[0,0,1,1,2,2,3,2,4,3,5,4,6,5,7,5,8,6,9,6,10,7],"p":[52.88,424.35,84.88,388.23,116.89,352.11,148.9,352.11,180.9,315.99,212.91,279.87,244.91,243.75,276.92,243.75,308.92,207.63,340.93,207.63,372.93,171.51]},{"k":"line","c":"#fffff8","s":"x","d":[0,0,1,0,2,0,3,1,4,1,5,1,6,1,7,2,8,2,9,3,10,3],"p":[52.88,424.35,84.88,424.35,116.89,424.35,148.9,388.23,180.9,388.23,212.91,388.23,244.91,388.23,276.92,352.11,308.92,352.11,340.93,315.99,372.93,315.99]},{"k":"line","c":"#0b7f61","s":"x","d":[0,0,1,0,2,0,3,1,4,1,5,1,6,1,7,2,8,2,9,3,10,3],"p":[52.88,424.35,84.88,424.35,116.89,424.35,148.9,388.23,180.9,388.23,212.91,388.23,244.91,388.23,276.92,352.11,308.92,352.11,340.93,315.99,372.93,315.99]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"},{"k":"annotation","c":"#0b7f61"}],"lg":[]} 0 2 4 6 8 10 Edges processed 0 2 4 6 8 Count after each edge Remaining components Successful unions Already connected 7 of 10 edges joined components; a–c, d–g and c–e closed cycles
  • 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 against knotkit/disjoint-set.

ExportReturnsDoes
indexedDisjointSetIndexedDisjointSetDense integer disjoint set over `0..size - 1`: parent and rank in typed arrays, no element-to-index registry; `append` mints the next index.
objectDisjointSetGrowableDisjointSet<T>Growable disjoint set over any values, keeping one `{ parent, rank }` object per element and a registry from value to dense index.
structOfArraysDisjointSetGrowableDisjointSet<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
MemberCost
sizeO(1)
setCountO(1)
hasO(1)
uniteO(alpha(n)) amortized
areConnectedO(alpha(n)) amortized
findO(alpha(n)) amortized
elementsO(1) per step, O(n) total
setsO(n * alpha(n))
appendO(1) amortized
objectDisjointSet 9 members
MemberCost
sizeO(1)
setCountO(1)
hasO(1) average
uniteO(alpha(n)) amortized
areConnectedO(alpha(n)) amortized
findO(alpha(n)) amortized
elementsO(1) per step, O(n) total
setsO(n * alpha(n))
addO(1) amortized
structOfArraysDisjointSet 9 members
MemberCost
sizeO(1)
setCountO(1)
hasO(1) average
uniteO(alpha(n)) amortized
areConnectedO(alpha(n)) amortized
findO(alpha(n)) amortized
elementsO(1) per step, O(n) total
setsO(n * alpha(n))
addO(1) amortized
InputTypeGet one from
element encoding for a binary artifact of a generic layout, which no artifact carries backElementCodec<T>knotkit/wire
element validation for a JSON artifact, whose projections carry no element types(value: unknown) => value is Tthe caller

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

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
If you need to…Use instead
look up a value by key, or check whether a single value is presentSet, Map
sort edges by weight before merging them one by oneArray.prototype.sort with a comparator
read membership as it was at an earlier moment while the set keeps changingknotkit/snapshot-set
split a group apart, or undo a mergerebuild the structure from the unions you kept, because a merge is never undone
walk a graph's adjacency, or find the shortest pathknotkit/graph

Measured by the suite in 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.

Prompt · knotkit/disjoint-set
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/