1. Email owner
Map each email to the first account that claimed it.
const emailToId = new Map()Typorithm · medium
Step 1 of 8 · intro card
Union-Find
Union accounts that share any email via an email→owner map, then group every email by its root and emit name plus sorted emails.
Accounts belong together if they share at least one email, a transitive relation perfect for union-find.
Map each email to the first account that owns it; a repeat email unions the two accounts.
Finally group all emails by their account's root, sort each group, and prepend the owner's name.
Union accounts sharing an email.
Group emails by DSU root.
Sort emails, prepend the name.
function accountsMerge(accounts) {
const uf = new UnionFind(accounts.length);
const emailToId = new Map();
for (let i = 0; i < accounts.length; i += 1) {
for (let j = 1; j < accounts[i].length; j += 1) {
const email = accounts[i][j];
if (emailToId.has(email)) {
uf.union(i, emailToId.get(email));
} else {
emailToId.set(email, i);
}
}
}
const groups = new Map();
for (const [email, id] of emailToId) {
const root = uf.find(id);
if (!groups.has(root)) {
groups.set(root, []);
}
groups.get(root).push(email);
}
const result = [];
for (const [root, emails] of groups) {
emails.sort();
result.push([accounts[root][0], ...emails]);
}
return result;
}Connect each part of the code to the concept before you type.
Map each email to the first account that claimed it.
const emailToId = new Map()Two accounts sharing an email belong together.
uf.union(i, emailToId.get(email))All emails under one root form a single merged account.
const root = uf.find(id)Prepend the owner's name to the sorted emails.
result.push([accounts[root][0], ...emails])Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.