DSU05 - Editorial

Problem Link - Naive DSU Implementation

Problem Statement -

Implement the dsuFind and dsuUnion functions of DSU in the code editor.

Approach:

The key idea of this code is to utilize the Disjoint Set Union (DSU) or Union-Find data structure to efficiently handle a collection of disjoint (non-overlapping) sets. This structure supports two main operations:

dsuFind(int a):

  • If parent[a] equals a, it means that a is the leader of its set. Thus, the function returns a.

  • If parent[a] does not equal a, the function recursively calls itself with parent[a] until it finds the leader. This implements the path compression technique, making future queries faster by directly linking elements to their set leader.

dsuUnion(int a, int b):

  • It first finds the leaders of both a and b by calling dsuFind on both.

  • If the leaders are different, it updates the parent of leader_b to be leader_a, effectively merging the two sets.

  • This operation ensures that all elements of one set now point to the leader of the other set.

Time Complexity:

  • dsuFind: O(α(n)), where α is the inverse Ackermann function. This function grows very slowly, so it is nearly constant time for practical purposes.

  • dsuUnion: O(α(n)), for the same reasons as above.

Space Complexity:

  • O(n) for storing the parent array, where n is the number of elements.