Dsa
Union Find
Medium
Library Book Grouping
You are tasked with organizing a set of library books into groups based on their themes. Each theme is represented by a pair of book IDs that are related. Determine how many unique book groups exist after processing all theme relations.
Input format:
M
X1 Y1
X2 Y2
...
XM YM
Where M is the number of theme relations and Xi Yi are the pairs of related book IDs.
Output format:
An integer representing the number of unique book groups.
Example:
Input:
4
1 2
2 3
4 5
5 6
Output:
2
Key concepts
union_findclusterscollections
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