I am working on the following problem:
In a room with people, we will define two persons are friends if they are directly or indirectly friends. If A is a friend with B, and B is a friend with C, then A is a friend of C too. A group of friends is a group of persons where any two persons in the group are friends. Given the list of persons that are directly friends, find the smallest group of friends..
Example: Input:
1<->6
2<->7
3<->8
4<->9
2<->6
3<->5
Groups:
1-6-2-7
3-8-5
4-9
The number of people in the smallest group is 2 i.e. 4-9 so we should return 2.
I came up with the code below but I don't understand how to use this holder
map now to get the required output. I am kinda confused here. What is the best way to solve this problem?
private static int findGroups(final List<List<Integer>> inputs) {
if (inputs == null || inputs.isEmpty()) {
return 0;
}
int count = Integer.MAX_VALUE;
Map<Integer, List<Integer>> holder = new HashMap<>();
for (List<Integer> input : inputs) {
// storing it in bidirectional way in the map
List<Integer> l =
holder.containsKey(input.get(0)) ? holder.get(input.get(0)) : new ArrayList<Integer>();
l.add(input.get(1));
holder.put(input.get(0), l);
List<Integer> l1 =
holder.containsKey(input.get(1)) ? holder.get(input.get(1)) : new ArrayList<Integer>();
l1.add(input.get(0));
holder.put(input.get(1), l1);
}
System.out.println(holder);
// use holder map to get the smaller group here?
return count;
}
Looks like I need to use recursion here to get smaller groups?
Stronger Bonds A smaller inner circle means you can invest time in the relationships you have with each of your close friends. For instance, if you have two close friends, you can easily make time to see them at least once each week.
The 'Circle of Friends' intervention is aimed primarily at improving the inclusion of children with challenging behaviour, SEN or personal concerns within mainstream schools. It works by gathering the student's peers in a circle of friendly support to help the young person with their problem solving.
The number of friends in your inner circle should be small, typically less than 5 people.
Is there any better way to solve this problem?
A better approach is to use a disjoint-set data structure:
By the way, the technical name for the operation you're performing is transitive closure: the "are friends" relation is the transitive closure of the "are directly friends" relation. (However, the algorithms described at the Wikipedia article for that are not optimal for your problem, because they don't take advantage of the fact that your relation is symmetric.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With