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?
  1. A. 3
  2. B. 2
  3. C. 4
  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

Exams that ask this topic