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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 0 0 3 4
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 0 0 3 4
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Relabel every member of one component during union so find remains constant time.
- 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.
