ADVANCED DATA STRUCTURES PROGRAM • LEVEL 9 — DISJOINT SETS

Count Dynamic Connected Components

Learn how to count dynamic connected components using a clear C program.

IntermediateUnion-findConnectivity

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Components = 2

COMPLETE C PROGRAM

Complete C implementation

ads-dsu-count-components.c
Open in compiler
#include <stdio.h>

int parent[10], rank_value[10], set_size[10];
void initialize(int count) { for (int i = 0; i < count; i++) { parent[i] = i; rank_value[i] = 0; set_size[i] = 1; } }
int find_root(int value) { return parent[value] == value ? value : (parent[value] = find_root(parent[value])); }
void unite_rank(int first, int second)
{
    first = find_root(first); second = find_root(second);
    if (first == second) return;
    if (rank_value[first] < rank_value[second]) { int temp = first; first = second; second = temp; }
    parent[second] = first; set_size[first] += set_size[second];
    if (rank_value[first] == rank_value[second]) rank_value[first]++;
}

int main(void)
{
    initialize(6);
    int components = 6, edges[][2] = {{0, 1}, {1, 2}, {3, 4}, {2, 4}};
    for (int edge = 0; edge < 4; edge++) {
        int first = find_root(edges[edge][0]), second = find_root(edges[edge][1]);
        if (first != second) { unite_rank(first, second); components--; }
    }
    printf("Components = %d\n", components);
    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

Components = 2
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Decrease the component counter only when an edge joins two different roots.
  3. Display the computed result.

Decrease the component counter only when an edge joins two different roots.

EFFICIENCY

Time and space complexity

Time complexity

O((n + m) alpha(n))

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.