ADVANCED DATA STRUCTURES PROGRAM • LEVEL 9 — DISJOINT SETS

Implement Quick-Find Disjoint Sets

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

IntermediateUnion-findConnectivity

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
0 0 0 3 4

COMPLETE C PROGRAM

Complete C implementation

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

int main(void)
{
    int id[] = {0, 1, 2, 3, 4};
    int pairs[][2] = {{0, 1}, {1, 2}};
    for (int edge = 0; edge < 2; edge++) {
        int from = id[pairs[edge][1]], to = id[pairs[edge][0]];
        for (int index = 0; index < 5; index++) if (id[index] == from) id[index] = to;
    }
    for (int index = 0; index < 5; index++) printf("%d%c", id[index], index == 4 ? '\n' : ' ');
    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 0 0 3 4
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Relabel every member of one component during union so find remains constant time.
  3. Display the computed result.

Relabel every member of one component during union so find remains constant time.

EFFICIENCY

Time and space complexity

Time complexity

O(n) union

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.