0
0
DSA Cprogramming~10 mins

Union Find Disjoint Set Data Structure in DSA C - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the parent array so each element is its own parent.

DSA C
for (int i = 0; i < n; i++) {
    parent[i] = [1];
}
Drag options to blanks, or click blank then click option'
An
B0
C-1
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Setting all parents to 0 or -1 instead of their own index.
Using n as parent which is out of array bounds.
2fill in blank
medium

Complete the code to find the root parent of element x with path compression.

DSA C
int find(int x) {
    if (parent[x] != x) {
        parent[x] = [1];
    }
    return parent[x];
}
Drag options to blanks, or click blank then click option'
Afind(parent[x])
Bparent[parent[x]]
Cparent[x]
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning parent[x] to parent[parent[x]] which may not be root.
Returning x directly without path compression.
3fill in blank
hard

Fix the error in the union function to correctly merge two sets by their root parents.

DSA C
void union_sets(int a, int b) {
    a = find(a);
    b = find(b);
    if (a != b) {
        parent[[1]] = [2];
    }
}
Drag options to blanks, or click blank then click option'
Aa
Bb
Cparent[a]
Dparent[b]
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning parent[parent[a]] or parent[parent[b]] which is incorrect.
Assigning parent[b] = a instead of parent[a] = b.
4fill in blank
hard

Fill both blanks to implement union by rank optimization.

DSA C
void union_sets(int a, int b) {
    a = find(a);
    b = find(b);
    if (a != b) {
        if (rank[a] < rank[b]) {
            parent[[1]] = [2];
        } else {
            parent[b] = a;
            if (rank[a] == rank[b]) {
                rank[a]++;
            }
        }
    }
}
Drag options to blanks, or click blank then click option'
Aa
Bb
Cparent[a]
Dparent[b]
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping a and b incorrectly in assignment.
Not updating rank when ranks are equal.
5fill in blank
hard

Fill all three blanks to implement a function that checks if two elements are in the same set.

DSA C
int is_same_set(int a, int b) {
    return [1](a) == [2](b);
}

void make_set(int v) {
    parent[v] = v;
    rank[v] = [3];
}
Drag options to blanks, or click blank then click option'
Afind
Bunion_sets
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using union_sets instead of find in is_same_set.
Initializing rank to 1 instead of 0.