# Find which items are connected

> A disjoint set merges groups as links arrive and answers whether two items are in the same group.

**Few items**

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

const accounts = objectDisjointSet(['ada', 'grace', 'alan', 'edsger'])

// Accounts that share an email address belong to the same person.
accounts.unite('ada', 'grace') // true
accounts.unite('grace', 'alan') // true
accounts.unite('ada', 'alan') // false, already connected

accounts.areConnected('ada', 'alan') // true
accounts.areConnected('ada', 'edsger') // false
accounts.setCount // 2
```

**Thousands of items**

```ts
import { objectDisjointSet } from 'knotkit/disjoint-set'
import { splitmix32, uniformInt } from 'knotkit/prng'
import { shuffled } from 'knotkit/sampling'

const random = splitmix32(2026)

// 10,000 accounts. A chain of 9,999 links joins them all, and 1,000 seeded extra links repeat what the chain already joins.
const accounts = objectDisjointSet(Array.from({ length: 10_000 }, (_, index) => `account-${index}`))
const chain = Array.from({ length: 9_999 }, (_, index) => [index, index + 1] as const)
const extra = Array.from({ length: 1_000 }, () => {
  const left = uniformInt(random, 10_000)

  return [left, (left + 1 + uniformInt(random, 9_999)) % 10_000] as const
})
const links = shuffled(random, [...chain, ...extra])

let merged = 0
let redundant = 0

for (const [left, right] of links) {
  if (accounts.unite(`account-${left}`, `account-${right}`)) {
    merged += 1
  } else {
    redundant += 1
  }
}

accounts.setCount // 1
merged // 9999, one per account after the first
redundant // 1000, links between accounts that were already connected
accounts.areConnected('account-0', 'account-9999') // true
```

`unite` returns `false` when the two items were already connected, which is how Kruskal and cycle detection count useful edges. Use `indexedDisjointSet` when the items are dense integer ids.

**Modules:** [`knotkit/disjoint-set`](/modules/disjoint-set/) · [API reference](/reference/knotkit/disjoint-set/)
