MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / UnionFind

Class UnionFind

kotlin/Graphs/ConnectTheDots.kt:1–30  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class UnionFind(size: Int) {
2 private val parent = IntArray(size) { it }
3 private val size = IntArray(size) { 1 }
4
5 fun union(x: Int, y: Int): Boolean {
6 var repX = find(x)
7 var repY = find(y)
8 if (repX != repY) {
9 if (size[repX] > size[repY]) {
10 parent[repY] = repX
11 size[repX] += size[repY]
12 } else {
13 parent[repX] = repY
14 size[repY] += size[repX]
15 }
16 // Return true if both groups were merged.
17 return true
18 }
19 // Return false if the points belong to the same group.
20 return false
21 }
22
23 fun find(x: Int): Int {
24 if (x == parent[x]) {
25 return x
26 }
27 parent[x] = find(parent[x])
28 return parent[x]
29 }
30}
31
32fun connectTheDots(points: List<List<Int>>): Int {
33 val n = points.size

Callers 1

connectTheDotsFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected