Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Count connected components of an undirected graph given as an edge list on n nodes.
Problem: Count connected components of an undirected graph given as an edge list on n nodes.
int find(vector<int>& p, int x) { return p[x] == x ? x : p[x] = find(p, p[x]); }
int components(int n, vector<pair<int,int>>& e) {
vector<int> p(n);
iota(p.begin(), p.end(), 0);
int comps = n;
for (auto [u, v] : e) {
int a = find(p, u), b = find(p, v);
if (a != b) { p[a] = b; comps--; }
}
return comps;
}
// n = 7, e = {{0,1},{1,2},{3,4},{2,0},{5,5}}What does components return?- A. 3
- B. 2
- C. 4
- D. 5
Correct answer: C. 4
Start with n components and subtract one for every union that merges two different sets. 0–1, 1–2 and 3–4 merge (3 merges); 2–0 is already connected and 5–5 is a self-loop. 7 − 3 = 4: {0,1,2}, {3,4}, {5}, {6}. Isolated node 6 has no edge but still counts. Near O(E + V).
More Coding Interview Problems questions
- Problem: Return the k-th largest value in a stream of scores using a min-heap of size k. python import heapq def kthlargest(a, k): h = []…
- Problem: From n = 10⁶ log entries, return the k = 10 most frequent error codes. Which approach is the most efficient?
- Problem: Merge k sorted lists of order timestamps into one sorted list. python import heapq def mergek(lists): h = [(l[0], i, 0) for i, l…
- Problem: Maintain the median of a stream with two heaps (max-heap for the lower half, min-heap for the upper half). python import heapq…
- Problem: Connect ropes into one; joining two ropes costs the sum of their lengths. Find the minimum total cost. python import heapq def…
- Problem: Return the k points closest to the origin (ties broken by smaller index). python import heapq pts = [(3, 3), (5, -1), (-2, 4)…