Accounts Merge LeetCode solution in JavaScript

1
/**
2
* @param {string[][]} accounts
3
* @return {string[][]}
4
*/
5

6
var accountsMerge = function (accounts) {
7
let graph = {};
8
let nameDict = {};
9

10
for (let acc of accounts) {
11
let name = acc[0];
12
nameDict[acc[1]] = name;
13
for (let i = 1; i < acc.length; i++) {
14
if (!graph[acc[i]]) graph[acc[i]] = new Set();
15
nameDict[acc[i]] = name;
16
if (i != 1) {
17
graph[acc[1]].add(acc[i]);
18
graph[acc[i]].add(acc[1]);
19
}
20
}
21
}
22

23
let res = [];
24
let visited = new Set();
25

26
let dfs = function (key) {
27
visited.add(key);
28
let emails = [key];
29
graph[key].forEach((e) => {
30
if (!visited.has(e)) {
31
emails.push(...dfs(e));
32
}
33
});
34

35
return emails;
36
};
37

38
for (let key in graph) {
39
if (!visited.has(key)) {
40
let temp = dfs(key);
41
temp.sort();
42
temp.unshift(nameDict[temp[0]]);
43
res.push(temp);
44
}
45
}
46

47
return res;
48
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0