Skip to content

Instantly share code, notes, and snippets.

@caovanbi235
Last active March 31, 2025 05:22
Show Gist options
  • Save caovanbi235/fa9e46e7e31ccc813c59b78a7397c926 to your computer and use it in GitHub Desktop.
Save caovanbi235/fa9e46e7e31ccc813c59b78a7397c926 to your computer and use it in GitHub Desktop.
Ruby UnionFind
class UnionFind
def initialize(n)
@d = Array.new(n, -1)
end
def root(x)
return x if @d[x] < 0
@d[x] = root(@d[x])
end
def is_same?(x, y)
root(x) == root(y)
end
def unite(x, y)
x = root(x)
y = root(y)
return if x == y
x, y = y, x if @d[x] > @d[y]
@d[x] += @d[y]
@d[y] = x
end
def size(x)
-@d[root(x)]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment