Dsa
Union Find
Easy
Friend Groups
You are given a number of friendship relations among people represented as pairs of integers. Each integer identifies a person, and a pair (a, b) indicates that person 'a' is friends with person 'b'. Your task is to find the total number of distinct friend groups in these relations. A friend group is defined as a group of people where each person is connected directly or indirectly through friendship relations.
Input:
The first line contains an integer N (1 ≤ N ≤ 1000) representing the number of pairs of friendships.
The next N lines each contain two integers a and b (1 ≤ a, b ≤ 1000), representing a friendship between person 'a' and person 'b'.
Output:
Output 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_findgroupssocial_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