Each account is [name, ...emails]. Two accounts belong to the same person if they share any email. Merge them and return each person's name followed by their emails in sorted order.
Give each account an id. When an email was already seen in another account, union the two accounts. Finally group emails by their account's root.
1function accountsMerge(accounts: string[][]): string[][] {2const parent = accounts.map((_, i) => i);3const find = (x: number): number => (parent[x] === x ? x : (parent[x] = find(parent[x])));4const owner = new Map<string, number>();5accounts.forEach(([, ...emails], i) => {6for (const e of emails) {7if (owner.has(e)) parent[find(i)] = find(owner.get(e)!);8else owner.set(e, i);9}10});11const groups = new Map<number, string[]>();12for (const [e, i] of owner) {13const r = find(i);14if (!groups.has(r)) groups.set(r, []);15groups.get(r)!.push(e);16}17return [...groups].map(([r, es]) => [accounts[r][0], ...es.sort()]);18}
Each account is its own set.
Space: play/pause · ←/→: step