Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Return the number of provinces (connected components) from an adjacency matrix using DFS.
Problem: Return the number of provinces (connected components) from an adjacency matrix using DFS.
static int provinces(int[][] m) {
int n = m.length, c = 0;
boolean[] seen = new boolean[n];
for (int i = 0; i < n; i++)
if (!seen[i]) { c++; dfs(m, seen, i); }
return c;
}
static void dfs(int[][] m, boolean[] seen, int u) {
seen[u] = true;
for (int v = 0; v < m.length; v++) if (m[u][v] == 1 && !seen[v]) dfs(m, seen, v);
}
// provinces({{1,1,0,0},{1,1,0,0},{0,0,1,0},{0,0,0,1}})What does the call return?- A. 2
- B. 3
- C. 4
- D. 1
Correct answer: B. 3
Cities 0 and 1 are connected; 2 and 3 are isolated (only self-loops on the diagonal). Each DFS launched from an unseen city marks a whole province: 3. With an adjacency matrix this is O(n²).
More Coding Interview Problems questions
- Problem: Find the town judge: trusted by everyone else and trusting nobody (−1 if none). python def judge(n, trust): score = [0] (n + 1)…
- Problem: Find the cheapest network latency to reach all nodes from node k (network delay = max shortest distance). python import heapq def…
- Problem: Clone check – count how many nodes a BFS reaches from node 0 in a directed graph that contains a cycle. python from collections…
- Problem: Print a matrix in spiral order (clockwise from the top-left). cpp vector<int> spiral(vector<vector<int>>& m) { vector<int> out…
- Problem: Rotate an n × n image 90° clockwise in place. python def rotate(m): n = len(m) for i in range(n): for j in range(i + 1, n)…
- Problem: Set the whole row and column to 0 for every 0 in a matrix. python def zeroes(m): R, C = len(m), len(m[0]) rows = {r for r in…