We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Basically you just build separate trees for each "disjoint set" and whenever you need to merge two of them, you make the root of the smaller set a child of the root of the larger set.
Friend Circle Queries
You are viewing a single comment's thread. Return to all comments →
This problem is solved using a data structure called a Disjoint Set. Geeks for geeks has a pretty good article on them here: https://www.geeksforgeeks.org/disjoint-set-data-structures-java-implementation/
Basically you just build separate trees for each "disjoint set" and whenever you need to merge two of them, you make the root of the smaller set a child of the root of the larger set.
Hackerrank has a few other problems setup to get you used to using this data structure. If you're interested, you can find them here: https://www.hackerrank.com/domains/data-structures?filters%5Bsubdomains%5D%5B%5D=disjoint-set