Overview
Given a list of accounts where each account is [name, email1, email2, ...], merge accounts belonging to the same person. Two accounts belong to the same person if they share any email. Return merged accounts with emails sorted, name first.
Constraints
1 <= accounts.length <= 10001 <= accounts[i].length <= 10- All emails are valid and lowercase.
Examples
accountsMerge([ ["John","john@mail","john_work@mail"], ["John","john@mail","john00@mail"], ["Mary","mary@mail"], ["John","johnny@mail"] ]); // => [ // ["John","john00@mail","john@mail","john_work@mail"], // ["John","johnny@mail"], // ["Mary","mary@mail"] // ]
Solution
Reveal solution
function accountsMerge(accounts) {
const parent = {};
function find(x) { if (parent[x] !== x) parent[x] = find(parent[x]); return parent[x]; }
function union(a, b) { parent[find(a)] = find(b); }
const emailToName = {};
for (const [name, ...emails] of accounts) {
for (const e of emails) {
if (!parent[e]) parent[e] = e;
emailToName[e] = name;
union(emails[0], e);
}
}
const groups = {};
for (const email of Object.keys(parent)) {
const root = find(email);
if (!groups[root]) groups[root] = [];
groups[root].push(email);
}
return Object.values(groups).map(emails => {
emails.sort();
return [emailToName[emails[0]], ...emails];
}).sort((a, b) => a[0].localeCompare(b[0]) || a[1].localeCompare(b[1]));
}Resources
accounts-merge.js
Accounts Merge
mediumcodingAlgorithmsUnion Find
Overview
Given a list of accounts where each account is [name, email1, email2, ...], merge accounts belonging to the same person. Two accounts belong to the same person if they share any email. Return merged accounts with emails sorted, name first.
Constraints
1 <= accounts.length <= 10001 <= accounts[i].length <= 10- All emails are valid and lowercase.
Examples
accountsMerge([ ["John","john@mail","john_work@mail"], ["John","john@mail","john00@mail"], ["Mary","mary@mail"], ["John","johnny@mail"] ]); // => [ // ["John","john00@mail","john@mail","john_work@mail"], // ["John","johnny@mail"], // ["Mary","mary@mail"] // ]
Solution
Reveal solution
function accountsMerge(accounts) {
const parent = {};
function find(x) { if (parent[x] !== x) parent[x] = find(parent[x]); return parent[x]; }
function union(a, b) { parent[find(a)] = find(b); }
const emailToName = {};
for (const [name, ...emails] of accounts) {
for (const e of emails) {
if (!parent[e]) parent[e] = e;
emailToName[e] = name;
union(emails[0], e);
}
}
const groups = {};
for (const email of Object.keys(parent)) {
const root = find(email);
if (!groups[root]) groups[root] = [];
groups[root].push(email);
}
return Object.values(groups).map(emails => {
emails.sort();
return [emailToName[emails[0]], ...emails];
}).sort((a, b) => a[0].localeCompare(b[0]) || a[1].localeCompare(b[1]));
}Resources
NameTopicDifficulty
103 of 103 problems