Question bank › Union Find
Dsa Union Find Easy

City Connections

Cities are connected through direct roads. Each city can be represented by an integer ID from 0 to n-1. Given a list of city pairs representing direct roads, determine how many distinct connected components exist in the city network, where each component is a group of cities connected either directly or indirectly. Input: - The first line of input contains an integer n (1 <= n <= 100), the number of cities. - The second line contains an integer m (0 <= m <= n*(n-1)/2), the number of direct roads. - Each of the following m lines contains two integers a and b, representing a direct road between city a and city b. Output: - Print the number of distinct connected components of cities. Example: Input: 5 3 0 1 1 2 3 4 Output: 2

Key concepts

union_findcitiesconnections

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
Part of InterviewLab's verified interview question bank. We show the prompt and concepts to practise with — never a copy-paste solution.