Data Structures & Algorithms

Union-Find/Disjoint-Set Interview Questions

Tackle coding interview questions on the Union-Find/Disjoint-Set data structure. Our AI-powered guide provides expert insights, practice problems, and personalized feedback to help you succeed.

Number of Connected Components in an Undirected Graph

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.

class Solution {   countComponents(n, edges) {     let parent = Array.from({length: n}, (_, i) => i);     let rank = Array(n).fill(1);
    function find(i) {       if (parent[i] === i) return i;       parent[i] = find(parent[i]);       return parent[i];     }
    function union(i, j) {       let rootI = find(i);       let rootJ = find(j);       if (rootI !== rootJ) {         if (rank[rootI] > rank[rootJ]) {           parent[rootJ] = rootI;         } else if (rank[rootI] < rank[rootJ]) {           parent[rootI] = rootJ;         } else {           parent[rootJ] = rootI;           rank[rootI] += 1;         }         return 1;       }       return 0;     }
    let components = n;     for (const [i, j] of edges) {       components -= union(i, j);     }     return components;   } }

The Union-Find data structure is ideal for this problem. We initialize each node as a separate component. Then, we iterate through the edges, and for each edge, we union the two nodes. If they were not already in the same set, we decrement the number of components. The final count is the answer.

Related Algorithm Guides

Explore more algorithm interview guides powered by AI coaching

Ai Powered Mock Interviews
AI-powered interview preparation guide
Legal Tech Software Developer Interview Preparation
AI-powered interview preparation guide
Slide Deck Presentation Interview Tips
AI-powered interview preparation guide
Technical Demo Interview Preparation
AI-powered interview preparation guide