-
Notifications
You must be signed in to change notification settings - Fork 0
/
accounts_merge.py
43 lines (34 loc) · 1.37 KB
/
accounts_merge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from ast import List
import collections
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def union(self, index1: int, index2: int):
self.parent[self.find(index2)] = self.find(index1)
def find(self, index: int) -> int:
if self.parent[index] != index:
self.parent[index] = self.find(self.parent[index])
return self.parent[index]
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
emailToIndex = dict()
emailToName = dict()
for account in accounts:
name = account[0]
for email in account[1:]:
if email not in emailToIndex:
emailToIndex[email] = len(emailToIndex)
emailToName[email] = name
uf = UnionFind(len(emailToIndex))
for account in accounts:
firstIndex = emailToIndex[account[1]]
for email in account[2:]:
uf.union(firstIndex, emailToIndex[email])
indexToEmails = collections.defaultdict(list)
for email, index in emailToIndex.items():
index = uf.find(index)
indexToEmails[index].append(email)
ans = list()
for emails in indexToEmails.values():
ans.append([emailToName[emails[0]]] + sorted(emails))
return ans