-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path721-accounts-merge.js
More file actions
53 lines (51 loc) · 1.2 KB
/
721-accounts-merge.js
File metadata and controls
53 lines (51 loc) · 1.2 KB
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
/**
* @param {string[][]} accounts
* @return {string[][]}
*/
var accountsMerge = function(accounts) {
let emailToNames = {}
let graph = {}
for(let i=0; i<accounts.length; i++) {
const [name, ...emails] = accounts[i]
const firstEmail = emails[0]
for(let j=0; j<emails.length; j++) {
const email = emails[j]
graph[firstEmail] = graph[firstEmail] || []
graph[firstEmail].push(email)
graph[email] = graph[email] || []
graph[email].push(firstEmail)
emailToNames[email] = name
}
}
let seen = {}
let toExplore = []
let res = []
let keys = Object.keys(graph)
for(let i=0; i<keys.length; i++) {
let u = keys[i]
if(!seen[u]) {
toExplore.push(u)
seen[u] = true
}
let emails = []
while(toExplore.length > 0) {
u = toExplore.pop()
emails.push(u)
if(graph[u]) {
for(let j=0; j<graph[u].length; j++) {
let v = graph[u][j]
if(!seen[v]) {
toExplore.push(v)
seen[v] = true
}
}
}
}
if(emails.length > 0) {
emails = emails.sort()
const name = emailToNames[emails[0]]
res.push([name, ...emails])
}
}
return res
};