We are given a map of friends, where one person can have multiple friends. write a program to find all the friends for a person including mutual friends.
This question was asked in a DocuSign frontend interview at the Seattle location.
Example
Input:
const mapping = {
a: ['b', 'c'],
b: ['d', 'g'],
d: ['p', 'q'],
l: ['x', 'y']
};
console.log(friends(mapping, 'a'));
Output:
["b","c","d","g","p","q"]
// a -> [b, c]
// b -> [d, g]
// d -> [p, q]
To find mutual friends, we have to get the person’s friends list, if the list exits
- Add all the friends to the final list.
- Iterate the friends and recursive call the same function and check if there are friends for each of these friends.
- If friends are found, add them to the final list.
const friends = (mapping, person) => {
// get the friends list
const friendsList = mapping[person];
// if the friend's list exits
if(friendsList) {
// then get the list in the final output
const output = [...friendsList];
// iterate each friend of the list
for(let entry of friendsList){
// and if mutual friends for these friends exit
// add them to the final list
output.push(...friends(mapping, entry));
}
// return the final list
return output;
}
// else return the empty list
return [];
}
Input: console.log(friends(mapping, 'a')); Output: ["b","c","d","g","p","q"]