-
Notifications
You must be signed in to change notification settings - Fork 2
/
sol2.py
74 lines (64 loc) · 2.4 KB
/
sol2.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from typing import List
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
connections_graph = self.createGraph(accounts)
email_to_username_mapper = self.getEmailToUsernameMapper(accounts)
groups = self.getEmailGroups(connections_graph)
final = []
for group in groups:
group.sort()
username = email_to_username_mapper[group[0]]
final.append(
[username] + group
)
return final
def getEmailGroups(self, connections_graph):
visited = {}
all_groups = []
to_process = list(connections_graph.keys())
for email in to_process:
cur_group = []
group_queue = [email]
while group_queue:
cur = group_queue.pop(0)
if cur in visited:
continue
visited[cur] = True
connected_emails = list(connections_graph[cur].keys())
group_queue += connected_emails
cur_group.append(cur)
all_groups.append(cur_group)
filtered = list(filter(lambda group: group, all_groups))
return filtered
def getEmailToUsernameMapper(self, accounts: List[List[str]]):
mapper = {}
for account_data in accounts:
username = account_data[0]
emails = account_data[1:]
for email in emails:
mapper[email] = username
return mapper
def createGraph(self, accounts: List[List[str]]):
graph = {}
for account_data in accounts:
emails = account_data[1:]
for i in range(len(emails)):
cur_email = emails[i]
if cur_email not in graph:
graph[cur_email] = {}
for j in range(i + 1, len(emails)):
connected_email = emails[j]
if connected_email not in graph:
graph[connected_email] = {}
graph[cur_email][connected_email] = True
graph[connected_email][cur_email] = True
return graph
accounts = [
["John","[email protected]","[email protected]"],
["John","[email protected]","[email protected]"],
["Mary","[email protected]"],
["John","[email protected]"]
]
s = Solution()
res = s.accountsMerge(accounts)
print(res)