Accounts Merge
Difficulty: Medium · Pattern: Union-Find · LeetCode #721
Each account is [name, email1, email2, …]. Two accounts belong to the same person if they share any email. People with the same name may still be different people. Merge the accounts and return each one as [name, …sorted emails]. The accounts can be listed in any order.
Example
text
[["John","[email protected]","[email protected]"],
["John","[email protected]","[email protected]"],
["Mary","[email protected]"],
["John","[email protected]"]]
→
[["John","[email protected]","[email protected]","[email protected]"],
["Mary","[email protected]"],
["John","[email protected]"]]Hints
- Names are not identifiers, emails are. Merge on emails.
- Union every email in an account with that account's first email. Then group the emails by their root.
Approach
- For each account,
union(firstEmail, email)for every other email, and rememberowner[email] = name. - Group:
groups[find(email)].append(email)for every email. - Emit
[owner[root]] + sorted(group).
Union-Find over strings (a dict-based parent map) is a common interview twist. A DFS over an email graph (email ↔ email edges) works equally well. O(E log E) for the sorting, where E is the total number of emails.
Complexity
Time: O(E log E). Space: O(E).
Python solution
from collections import defaultdict
def accountsMerge(accounts):
parent, owner = {}, {}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for acc in accounts:
name, first = acc[0], acc[1]
for e in acc[1:]:
parent.setdefault(e, e)
owner[e] = name
ra, rb = find(first), find(e)
if ra != rb:
parent[rb] = ra
groups = defaultdict(list)
for e in parent:
groups[find(e)].append(e)
return [[owner[root]] + sorted(es) for root, es in groups.items()]JavaScript solution
function accountsMerge(accounts) {
const parent = new Map(), owner = new Map();
const find = (x) => { while (parent.get(x) !== x) { parent.set(x, parent.get(parent.get(x))); x = parent.get(x); } return x; };
for (const [name, first, ...rest] of accounts) {
for (const e of [first, ...rest]) {
if (!parent.has(e)) parent.set(e, e);
owner.set(e, name);
const ra = find(first), rb = find(e);
if (ra !== rb) parent.set(rb, ra);
}
}
const groups = new Map();
for (const e of parent.keys()) { const r = find(e); if (!groups.has(r)) groups.set(r, []); groups.get(r).push(e); }
return [...groups].map(([r, es]) => [owner.get(r), ...es.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))]);
}