Skip to content

Instantly share code, notes, and snippets.

@rubenhak
Created January 13, 2023 22:10
Show Gist options
  • Save rubenhak/fb328aa55397a4795da29b714d2d0b36 to your computer and use it in GitHub Desktop.
Save rubenhak/fb328aa55397a4795da29b714d2d0b36 to your computer and use it in GitHub Desktop.
JavaScript Disjoint Set Union
class DisjointSetUnion
{
constructor()
{
this.map = new Map();
}
find(x)
{
let other = this.map.has(x) ? this.map.get(x) : x;
if (other != x)
{
other = this.find(other);
this.map.set(x, other);
}
return other;
}
union(x, y)
{
this.map.set(this.find(x), this.find(y));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment