function accountsMerge(accounts) {
const parent = {};
const emailToName = {};
function find(x) {
if (parent[x] !== x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
function union(x, y) {
parent[find(x)] = find(y);
}
for (const account of accounts) {
const [name, ...emails] = account;
for (const email of emails) {
if (!parent[email]) parent[email] = email;
emailToName[email] = name;
union(emails[0], email);
}
}
const unions = {};
for (const email of Object.keys(parent)) {
const root = find(email);
if (!unions[root]) unions[root] = [];
unions[root].push(email);
}
const result = [];
for (const emails of Object.values(unions)) {
emails.sort();
result.push([emailToName[emails[0]], ...emails]);
}
return result;
}
console.log(accountsMerge([
["John", "johnsmith@mail.com", "john00@mail.com"],
["John", "johnnybravo@mail.com"],
["John", "johnsmith@mail.com", "john_newyork@mail.com"],
["Mary", "mary@mail.com"]
]));