Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Kotlin: 684. Redundant Connection #965

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 30, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions kotlin/684-Redundant-Connection.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
class Solution {
fun findRedundantConnection(edges: Array<IntArray>): IntArray {
val uf = UnionFind(edges.size)

for (edge in edges) {
val (u, v) = edge

if (uf.isConnected(u-1, v-1))
return intArrayOf(u, v)

uf.unify(u-1, v-1)
}

return intArrayOf(0)
}
}

class UnionFind(n : Int) {
val parent = IntArray(n) { it }
val rank = IntArray(n) { 1 }

fun unify(p: Int, q: Int) {
val rootP = find(p)
val rootQ = find(q)

if (rootP == rootQ)
return

if (rank[rootP] > rank[rootQ]) {
parent[rootQ] = parent[rootP]
rank[rootP] += rank[rootQ]
} else {
parent[rootP] = parent[rootQ]
rank[rootQ] += rank[rootP]
}
}

fun find(p: Int): Int {
var root = p
var curr = p

while (root != parent[root])
root = parent[root]

while (root != curr) {
val next = parent[curr]
parent[p] = parent[root]
curr = next
}

return root
}

fun isConnected(p: Int, q: Int): Boolean {
return find(p) == find(q)
}
}