0
0
DSA Cprogramming~30 mins

Union Find Disjoint Set Data Structure in DSA C - Build from Scratch

Choose your learning style9 modes available
Union Find Disjoint Set Data Structure
📖 Scenario: Imagine you have a group of friends, and you want to know if two friends are in the same friend circle. A friend circle means everyone is connected directly or through other friends. We will use a Union Find Disjoint Set data structure to keep track of these friend circles.
🎯 Goal: You will build a simple Union Find Disjoint Set in C that can join two friend circles and check if two friends belong to the same circle.
📋 What You'll Learn
Create an array called parent to represent each friend's parent in the set
Create an array called rank to keep track of the tree height for optimization
Write a function find that returns the root parent of a friend with path compression
Write a function union_sets that joins two friend circles using rank to keep trees short
Write code to check if two friends are in the same friend circle using find
💡 Why This Matters
🌍 Real World
Union Find is used in social networks to find connected groups, in network connectivity, and in clustering problems.
💼 Career
Understanding Union Find helps in solving problems related to grouping, connectivity, and efficient merging in software engineering and competitive programming.
Progress0 / 4 steps
1
Create the parent and rank arrays
Create two arrays called parent and rank of size 5. Initialize parent so each friend is their own parent (0 to 4), and initialize rank with all zeros.
DSA C
Hint

Use a for loop from 0 to 4 to set parent[i] = i and rank[i] = 0.

2
Write the find function with path compression
Write a function called find that takes an integer x and returns the root parent of x. Use path compression by setting parent[x] to the root parent during the search.
DSA C
Hint

Check if parent[x] is not x. If so, call find recursively and update parent[x].

3
Write the union_sets function to join two sets
Write a function called union_sets that takes two integers a and b. Find their root parents using find. If they are different, attach the smaller rank tree under the bigger rank tree. If ranks are equal, attach b under a and increase rank[a] by 1.
DSA C
Hint

Use find on both a and b. Compare ranks and attach the smaller tree under the bigger one. If equal, attach b under a and increase rank[a].

4
Check if two friends are in the same set and print result
In main, use union_sets to join friends 0 and 1, and friends 1 and 2. Then check if friends 0 and 2 are in the same set by comparing find(0) and find(2). Print "Yes" if they are in the same set, otherwise print "No".
DSA C
Hint

Call union_sets(0, 1) and union_sets(1, 2). Then compare find(0) and find(2). Print "Yes" if equal, else "No".