- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 53 lines of Python from the credited upstream file accounts-merge.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.
1234 5import collections6 7 8class UnionFind(object):9 def __init__(self):10 self.set = []11 12 def get_id(self):13 self.set.append(len(self.set))14 return len(self.set)-115 16 def find_set(self, x):17 if self.set[x] != x:18 self.set[x] = self.find_set(self.set[x]) 19 return self.set[x]20 21 def union_set(self, x, y):22 x_root, y_root = map(self.find_set, (x, y))23 if x_root != y_root:24 self.set[min(x_root, y_root)] = max(x_root, y_root)25 26 27class Solution(object):28 def accountsMerge(self, accounts):29 """30 :type accounts: List[List[str]]31 :rtype: List[List[str]]32 """33 union_find = UnionFind()34 email_to_name = {}35 email_to_id = {}36 for account in accounts:37 name = account[0]38 for i in xrange(1, len(account)):39 if account[i] not in email_to_id:40 email_to_name[account[i]] = name41 email_to_id[account[i]] = union_find.get_id()42 union_find.union_set(email_to_id[account[1]],43 email_to_id[account[i]])44 45 result = collections.defaultdict(list)46 for email in email_to_name.keys():47 result[union_find.find_set(email_to_id[email])].append(email)48 for emails in result.values():49 emails.sort()50 return [[email_to_name[emails[0]]] + emails51 for emails in result.values()]52 53