DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS

Implement Disjoint-Set Union with Path Compression

Learn how to implement disjoint-set union with path compression using a clear C program.

IntermediateDSUPath compressionUnion by rank

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
0 and 2 connected: yes
0 and 4 connected: no

COMPLETE C PROGRAM

Complete C implementation

dsa-disjoint-set-union.c
Open in compiler
#include <stdio.h>

int find(int parent[], int value)
{
    if (parent[value] != value) parent[value] = find(parent, parent[value]);
    return parent[value];
}
void unite(int parent[], int rank[], int first, int second)
{
    int left = find(parent, first), right = find(parent, second);
    if (left == right) return;
    if (rank[left] < rank[right]) parent[left] = right;
    else if (rank[left] > rank[right]) parent[right] = left;
    else { parent[right] = left; rank[left]++; }
}

int main(void)
{
    int parent[6], rank[6] = {0};
    for (int index = 0; index < 6; index++) parent[index] = index;
    unite(parent, rank, 0, 1); unite(parent, rank, 1, 2); unite(parent, rank, 3, 4);
    printf("0 and 2 connected: %s\n", find(parent, 0) == find(parent, 2) ? "yes" : "no");
    printf("0 and 4 connected: %s\n", find(parent, 0) == find(parent, 4) ? "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

0 and 2 connected: yes
0 and 4 connected: no
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Compress find paths and attach the shallower representative tree beneath the deeper one.
  3. Display the computed result.

Compress find paths and attach the shallower representative tree beneath the deeper one.

EFFICIENCY

Time and space complexity

Time complexity

Almost O(1) amortized

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.