File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ # Time Complexity: O(N + E) - go through all nodes & edges.
2+ # Space Complexity: O(N) - store parent info for each node.
3+
4+ class Solution :
5+ def count_components (self , n : int , edges : List [List [int ]]) -> int :
6+
7+ # set up the Union-Find structure
8+ parent = [i for i in range (n )] # initially, each node is its own parent
9+ rank = [1 ] * n # used for optimization in Union operation
10+
11+ # find function (with path compression)
12+ def find (node ):
13+ if parent [node ] != node :
14+ parent [node ] = find (parent [node ]) # path compression
15+ return parent [node ]
16+
17+ # union function (using rank to keep tree flat)
18+ def union (node1 , node2 ):
19+ root1 , root2 = find (node1 ), find (node2 )
20+ if root1 != root2 :
21+ if rank [root1 ] > rank [root2 ]:
22+ parent [root2 ] = root1
23+ elif rank [root1 ] < rank [root2 ]:
24+ parent [root1 ] = root2
25+ else :
26+ parent [root2 ] = root1
27+ rank [root1 ] += 1
28+ return True # union was successful (i.e., we merged two components)
29+ return False # already in the same component
30+
31+ # connect nodes using Union-Find
32+ for a , b in edges :
33+ union (a , b )
34+
35+ # count unique roots (number of connected components)
36+ return len (set (find (i ) for i in range (n )))
You can’t perform that action at this time.
0 commit comments