- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 41 lines of Python from the credited upstream file minimize-malware-spread.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
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 4import collections5 6 7class UnionFind(object):8 def __init__(self, n):9 self.set = range(n)10 11 def find_set(self, x):12 if self.set[x] != x:13 self.set[x] = self.find_set(self.set[x]) 14 return self.set[x]15 16 def union_set(self, x, y):17 x_root, y_root = map(self.find_set, (x, y))18 if x_root == y_root:19 return False20 self.set[min(x_root, y_root)] = max(x_root, y_root)21 return True22 23 24class Solution(object):25 def minMalwareSpread(self, graph, initial):26 """27 :type graph: List[List[int]]28 :type initial: List[int]29 :rtype: int30 """31 union_find = UnionFind(len(graph))32 for i in xrange(len(graph)):33 for j in xrange(i+1, len(graph)):34 if graph[i][j] == 1:35 union_find.union_set(i, j)36 union_size = collections.Counter(union_find.find_set(i) for i in xrange(len(graph)))37 malware_count = collections.Counter(union_find.find_set(i) for i in initial)38 return min(initial, key=lambda x: [malware_count[union_find.find_set(x)] > 1,39 -union_size[union_find.find_set(x)],40 x])41