ADVANCED DATA STRUCTURES PROGRAM • LEVEL 9 — DISJOINT SETS

Implement Quick-Union Disjoint Sets

Learn how to implement quick-union disjoint sets using a clear C program.

IntermediateUnion-findConnectivity

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Connected = Yes

COMPLETE C PROGRAM

Complete C implementation

ads-dsu-quick-union.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int parent[] = {0, 1, 2, 3, 4};
    parent[1] = 0; parent[2] = 1;
    int root0 = 0, root2 = 2;
    while (parent[root0] != root0) root0 = parent[root0];
    while (parent[root2] != root2) root2 = parent[root2];
    printf("Connected = %s\n", root0 == root2 ? "Yes" : "No");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Connected = Yes
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Represent each component as a parent tree and compare its roots.
  3. Display the computed result.

Represent each component as a parent tree and compare its roots.

EFFICIENCY

Time and space complexity

Time complexity

O(h)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.