Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created March 17, 2020 08:15
Show Gist options
  • Save RP-3/1b41669d9a143b4123c5802417128601 to your computer and use it in GitHub Desktop.
Save RP-3/1b41669d9a143b4123c5802417128601 to your computer and use it in GitHub Desktop.
/**
* @param {string[][]} accounts
* @return {string[][]}
*/
var accountsMerge = function(accounts) {
const accountsWithEmail = new Map(); //<email: set(accountId)>
accounts.forEach((account, id) => {
for(let i=1; i<account.length; i++){
const email = account[i];
const name = account[0];
if(!accountsWithEmail.get(email)) accountsWithEmail.set(email, new Set());
accountsWithEmail.get(email).add(id);
}
});
const merge = (id) => {
const results = new Set();
const stack = [id];
const visited = new Set();
while(stack.length){
const currentAccountId = stack.pop();
if(visited.has(currentAccountId)) continue;
visited.add(currentAccountId);
const account = accounts[currentAccountId];
if(!account) continue;
accounts[currentAccountId] = null; // else we'll "merge" every account for all IDs
for(let i=1; i<account.length; i++){
const email = account[i];
results.add(email);
const sisterAccounts = accountsWithEmail.get(email) || new Set();
for(let sisterId of sisterAccounts) stack.push(sisterId);
}
}
return results;
};
const results = [];
for(let i=0; i<accounts.length; i++){
const account = accounts[i];
const id = i;
if(!account) continue;
const name = account[0];
const emails = Array.from(merge(id)).sort();
results.push([name].concat(emails));
}
return results;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment