Skip to content

Instantly share code, notes, and snippets.

@1rosehip
Last active November 29, 2018 17:51
Show Gist options
  • Save 1rosehip/b9a63846049a935df99c8572a7ad1d49 to your computer and use it in GitHub Desktop.
Save 1rosehip/b9a63846049a935df99c8572a7ad1d49 to your computer and use it in GitHub Desktop.
(() => {
'use strict';
/**
* get unique contacts
* @param {object} contacts
* @return {Array.<Array.<string>>}
*/
const getUniqueContacts = (contacts) => {
const keys = Object.keys(contacts);
if(keys.length <= 0) return [];
const result = [];
//create an adjacency list
const adjacencyList = {};
for(let i=0; i<keys.length; i++){
const key = keys[i];
adjacencyList[key] = new Set();
}
for(let i=0; i<keys.length; i++){
const key1 = keys[i];
const emailsList1 = contacts[key1];
for(let j=i+1; j<keys.length; j++){
const key2 = keys[j];
const emailsList2 = contacts[key2];
const set = new Set(emailsList1.concat(emailsList2));
if(emailsList1.length + emailsList2.length > set.size){
//contains common email
adjacencyList[key1].add(key2);
}
}
}
const visited = {};
//BFS to find connected components
for(let i=0; i<keys.length; i++){
if(visited[keys[i]]) continue;
//find connected components
const queue = [keys[i]];
const res = [];
while(queue.length > 0){
const item = queue.shift();
res.push(item);
visited[item] = true;
const children = adjacencyList[item];
children.forEach(child => {
if(!visited[child]){
queue.push(child);
}
});
}
result.push(res);
}
return result;
};
const contacts = {
c1: ['[email protected]', '[email protected]'],
c2: ['[email protected]'],
c3: ['[email protected]', '[email protected]'],
c4: ['[email protected]'],
c5: ['[email protected]'],
c6: ['[email protected]', '[email protected]']
};
console.log(getUniqueContacts(contacts));
/*
should return:
[(c1, c3, c5), (c2), (c4, c6) ]
*/
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment