Dsa
Union Find
Medium
Regional Consensus
N voters (0 to N-1) each have an initial 'Opinion' (an integer). When two groups of voters merge, the new group is 'Unified' if every single person in that group has the exact same opinion. If a group contains even two people with different initial opinions, it becomes 'Mixed' forever. Calculate the total number of voters who belong to a 'Unified' group after M merges.
Input Format:
Line 1: N (voters), M (merges).
Line 2: N integers (initial opinions).
Next M lines: Two integers u and v (voter u and voter v groups merge).
Output Format:
A single integer representing the number of voters in Unified groups.
Example:
Input:
4 2
10 10 20 20
0 1
1 2
Output:
0
Explanation:
Opinions: [10, 10, 20, 20]
- Merge (0,1): Group {0,1} all have opinion 10. Unified. Group {2}, {3} are unified. Total: 4.
- Merge (1,2): Group {0,1,2} has opinions {10, 10, 20}. Mixed. Group {3} is unified. Total: 1.
Wait, the example output is 1.
Key concepts
union_findstate_consistency
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