-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccounts Merge
More file actions
38 lines (29 loc) · 1016 Bytes
/
Accounts Merge
File metadata and controls
38 lines (29 loc) · 1016 Bytes
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
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
name = {}
n = len(accounts)
rep ={i : i for i in range(n)}
def find(node):
if rep[node] != node:
rep[node] = find(rep[node])
return rep[node]
def union(x, y):
xrep = find(x)
yrep = find(y)
if xrep!=yrep:
rep[yrep] = xrep
for idx in range(n):
for account in accounts[idx][1:]:
if account in rep:
union(rep[account],idx)
rep[account] = idx
ans = defaultdict(list)
for key in rep:
parent = find(key)
if isinstance(key,str):
ans[parent].append(key)
# print(ans)
answer = []
for key in ans:
answer.append([accounts[key][0]] + sorted(ans[key]))
return answer