- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 67 lines of Python from the credited upstream file number-of-operations-to-make-network-connected.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class UnionFind(object):5 def __init__(self, n):6 self.set = range(n)7 self.count = n8 9 def find_set(self, x):10 if self.set[x] != x:11 self.set[x] = self.find_set(self.set[x]) 12 return self.set[x]13 14 def union_set(self, x, y):15 x_root, y_root = map(self.find_set, (x, y))16 if x_root == y_root:17 return False18 self.set[max(x_root, y_root)] = min(x_root, y_root)19 self.count -= 120 return True21 22 23class Solution(object):24 def makeConnected(self, n, connections):25 """26 :type n: int27 :type connections: List[List[int]]28 :rtype: int29 """30 if len(connections) < n-1:31 return -132 union_find = UnionFind(n)33 for i, j in connections:34 union_find.union_set(i, j)35 return union_find.count - 136 37 383940import collections41 42 43class Solution2(object):44 def makeConnected(self, n, connections):45 """46 :type n: int47 :type connections: List[List[int]]48 :rtype: int49 """50 def dfs(i, lookup):51 if i in lookup:52 return 053 lookup.add(i)54 if i in G:55 for j in G[i]:56 dfs(j, lookup)57 return 158 59 if len(connections) < n-1:60 return -161 G = collections.defaultdict(list)62 for i, j in connections:63 G[i].append(j)64 G[j].append(i)65 lookup = set()66 return sum(dfs(i, lookup) for i in xrange(n)) - 167