![]() |
VOOZH | about |
Dynamic connectivity is a data structure that dynamically maintains the information about the connected components of graph. In simple words suppose there is a graph G(V, E) in which number of vertices V is constant but number of edges E is variable. There are three ways in which we can change the number of edges
In this article only Incremental connectivity is discussed. There are mainly two operations that need to be handled.
Example:
Input: V = 5, queries[][] = [[1, 0, 1], [2, 0, 1], [2, 1, 2], [1, 0, 2], [2, 1, 2], [1, 3, 4], [2, 2, 4], [1, 1, 3], [2, 2, 4]]
Output: true false true false true
Explanation: Initial state: Components = [[0], [1], [2], [3], [4]]
- Query [1, 0, 1]: Union(0,1) --> Components = [[0,1], [2], [3], [4]]
- Query [2, 0, 1]: Check connectivity --> Connected: true
- Query [2, 1, 2]: Check connectivity --> Connected: false
- Query [1, 0, 2]: Union(0,2) --> Components = [[0,1,2], [3], [4]]
- Query [2, 1, 2]: Check connectivity --> Connected: true
- Query [1, 3, 4]: Union(3,4) --> Components = [[0,1,2], [3,4]]
- Query [2, 2, 4]: Check connectivity --> Connected: false
- Query [1, 1, 3]: Union(1,3) --> Components = [[0,1,2,3,4]]
- Query [2, 2, 4]: Check connectivity --> Connected: true
Approach:
To solve the problems of incremental connectivity disjoint data structure is used. Here each connected component represents a set and if the two nodes belong to the same set it means that they are connected.
Implementation is given below here we are using union by rank and path compression
true false true false true
Time Complexity: O(α(n)), Inverse Ackermann, nearly constant time, because of path compression and union by rank optimization.
Space Complexity: O(n), For parent and rank arrays as arrays store disjoint set info for n elements.