Disjoint Set Problem
Disjoint Set Problem
1. Find(x): Determines which set an element x belongs to (with path compression for
efficiency).
2. Union(x, y): Merges the sets containing x and y (with union by rank/size for efficiency).
🔹 Time Complexity: O(α(N)) ≈ O(1) (almost constant time with path compression).
🔹 Best used when working with connected components, dynamic connectivity, and
merging sets.
You are given n nodes and an edge list edges, where edges[i] = [a, b] represents an undirected
edge between a and b.
Identification:
class DSU:
def __init__(self, n):
self.parent = list(range(n))
self.rank = [1] * n
# Example usage:
n = 5
edges = [[0,1], [1,2], [3,4]]
print(countConnectedComponents(n, edges)) # Output: 2 (two separate
components)
You are given an undirected graph with n nodes and edges[i] = [a, b].
class DSU:
def __init__(self, n):
self.parent = list(range(n))
# Example usage:
edges = [[0,1], [1,2], [2,3], [3,0]] # Cycle exists
print(hasCycle(4, edges)) # Output: True
Given a tree with n nodes (a connected graph with n nodes and n-1 edges), an extra edge is
added, creating a cycle.
Identification:
class DSU:
def __init__(self, n):
self.parent = list(range(n))
def findRedundantConnection(edges):
dsu = DSU(len(edges))
for u, v in edges:
if not dsu.union(u, v): # If adding this edge creates a cycle
return [u, v]
# Example usage:
edges = [[1,2], [1,3], [2,3]] # Edge [2,3] creates a cycle
print(findRedundantConnection(edges)) # Output: [2, 3]