DEV Community

nozomi-iida
nozomi-iida

Posted on

Learning Union-Find

What is Union-Find?

Union-Find is a data structure to manage groups in a tree structure.
When grouping in a tree structure, the advantage is that the following two points can be done quickly

  1. Check if x and y exist in a same group or not.
  2. If x and y exist in the same group, the affiliations of group x and group y can be easily merged.

Try to make Union-find Structure with Rust

struct UnionFind {
    par: Vec<usize>,
}

impl UnionFind {
    fn new(n: usize) -> Self {
        let mut par = vec![0; n];
        for i in 0..n {
            par[i] = i;
        }
        return Self { par };
    }

    fn root(&mut self, x: usize) -> usize {
        if self.par[x] == x {
            return x;
        }
        self.par[x] = self.root(self.par[x]);
        self.par[x]
    }

    fn unite(&mut self, x: usize, y: usize) {
        let rx = self.root(x);
        let ry = self.root(y);
        if rx == ry {
            return;
        }
        self.par[rx] = ry;
    }

    fn same(&mut self, x: usize, y: usize) -> bool {
        let rx = self.root(x);
        let ry = self.root(y);
        rx == ry
    }
}
Enter fullscreen mode Exit fullscreen mode
  • par: par[a] = b means "a's parent is b"
  • new: This function initializes everything as roots.
  • root: This function returns root.

For examples

  • When data x is a root, it returns x
  • When data x is not a root, par recursively traces back to the parent and return parental with

  • unite:
    This function merges two trees that don't have the same root.

  • same:
    This function return true if x and y have the same root.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay