721. Accounts Merge
At a Glance
- Topic: Array
- Pattern: Analyze Pattern
- Difficulty: Medium
- LeetCode: 721
Problem Statement
Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
Example 1:
Input: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com...
Approach & Solution Steps
Use Disjoint Set Union (DSU) or DFS to group emails. Map each email to an account index, union the indices, and aggregate emails by their root index.
Optimal JS Solution
function accountsMerge(accounts) {
const parent = Array.from({length: accounts.length}, (_, i) => i);
const find = i => parent[i] === i ? i : parent[i] = find(parent[i]);
const union = (i, j) => parent[find(i)] = find(j);
const emailToId = new Map();
for (let i = 0; i < accounts.length; i++) {
for (let j = 1; j < accounts[i].length; j++) {
const email = accounts[i][j];
if (emailToId.has(email)) union(i, emailToId.get(email));
else emailToId.set(email, i);
}
}
const idToEmails = new Map();
for (const [email, id] of emailToId.entries()) {
const root = find(id);
if (!idToEmails.has(root)) idToEmails.set(root, []);
idToEmails.get(root).push(email);
}
const res = [];
for (const [root, emails] of idToEmails.entries()) {
emails.sort();
res.push([accounts[root][0], ...emails]);
}
return res;
}Edge Cases & Pitfalls
- Always consider empty or null inputs.
- Watch out for off-by-one index errors.
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?