DSA interview question
A country has n cities. Some are directly connected by roads, and cities connected directly or indirectly belong to the same province. The road network is given as an adjacency matrix: isConnected[i][j] = 1 if cities i and j are directly connected. How many provinces are there? That's the number of connected components. Start a DFS from every city not yet visited and count how many times you had to start one.
Example: [[1,1,0], [1,1,0], [0,0,1]] → 2.
int findCircleNum(const vector<vector<int>>& isConnected);
| Input (adjacency matrix) | Output | Explanation |
|---|---|---|
[[1,1,0],[1,1,0],[0,0,1]] | 2 | {0, 1} and {2} |
[[1,0,0],[0,1,0],[0,0,1]] | 3 | No roads |
[[1,0,0,1],[0,1,1,0],[0,1,1,1],[1,0,1,1]] | 1 | 0-3-2-1 links everything |
[[1,1,1],[1,1,1],[1,1,1]] | 1 | |
[[1]] | 1 |
(Confirm: the matrix is symmetric with 1s on the diagonal; n ≤ 200.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in