|
| 1 | +/** |
| 2 | + * 721. Accounts Merge |
| 3 | + * https://leetcode.com/problems/accounts-merge/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a list of accounts where each element accounts[i] is a list of strings, where the first |
| 7 | + * element accounts[i][0] is a name, and the rest of the elements are emails representing emails |
| 8 | + * of the account. |
| 9 | + * |
| 10 | + * Now, we would like to merge these accounts. Two accounts definitely belong to the same person |
| 11 | + * if there is some common email to both accounts. Note that even if two accounts have the same |
| 12 | + * name, they may belong to different people as people could have the same name. A person can |
| 13 | + * have any number of accounts initially, but all of their accounts definitely have the same name. |
| 14 | + * |
| 15 | + * After merging the accounts, return the accounts in the following format: the first element of |
| 16 | + * each account is the name, and the rest of the elements are emails in sorted order. The accounts |
| 17 | + * themselves can be returned in any order. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {string[][]} accounts |
| 22 | + * @return {string[][]} |
| 23 | + */ |
| 24 | +var accountsMerge = function(accounts) { |
| 25 | + const parent = new Map(); |
| 26 | + const names = new Map(); |
| 27 | + const groups = new Map(); |
| 28 | + |
| 29 | + const find = node => { |
| 30 | + if (!parent.has(node)) parent.set(node, node); |
| 31 | + return parent.get(node) === node ? node : parent.set(node, find(parent.get(node))).get(node); |
| 32 | + }; |
| 33 | + |
| 34 | + for (const [name, ...emails] of accounts) { |
| 35 | + for (const email of emails) { |
| 36 | + names.set(email, name); |
| 37 | + find(email); |
| 38 | + parent.set(find(email), find(emails[0])); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + for (const email of parent.keys()) { |
| 43 | + const root = find(email); |
| 44 | + if (!groups.has(root)) groups.set(root, new Set()); |
| 45 | + groups.get(root).add(email); |
| 46 | + } |
| 47 | + |
| 48 | + return Array.from(groups, ([root, emails]) => [names.get(root), ...[...emails].sort()]); |
| 49 | +}; |
0 commit comments