Dsa
Union Find
Easy
Group Friends
You are given a list of pairs of friends. Each pair represents a direct friendship. Your task is to find the total number of distinct friend groups in these relationships. A friend group is formed when friends are directly or indirectly connected through other friends. Write a function that reads the number of friend pairs followed by the pairs themselves, and outputs the count of distinct friend groups.
Input format:
- The first line contains an integer N, the number of pairs.
- The following N lines each contain two integers A and B, representing a friendship between person A and person B.
Output format:
- A single integer representing the number of distinct friend groups.
Example:
Input:
5
1 2
2 3
4 5
5 6
7 8
Output:
4
Key concepts
union_findgroupingsocial_network
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now