The Count Unreachable Pairs of Nodes in an Undirected Graph interview question asks you to find how many pairs of nodes (u, v) exist such that there is no path between them. You are given an undirected graph with n nodes and an edge list. Since "unreachable" means the nodes belong to different connected components, the problem effectively asks you to find all components and calculate the pairs formed between them.
Microsoft and Snapchat frequently ask this graph interview pattern to test knowledge of connectivity. It evaluates your ability to use traversal algorithms like BFS/DFS or Disjoint Set Union (DSU) to group nodes. It also tests your combinatorics skills—calculating pairs without using O(n^2) nested loops.
The problem is solved in two steps:
Suppose and components are of size 3, 2, and 2.
total += 3 * (7-3) = 12. Remaining nodes = 4.total += 2 * (4-2) = 8. Remaining nodes = 2.total += 2 * (2-2) = 0.
Result: 20.Practice using Union-Find for connectivity problems. It's often easier to implement and can handle dynamic edge additions better than BFS/DFS, making it a favorite for interviewers.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count the Number of Complete Components | Medium | Solve | |
| Minimum Score of a Path Between Two Cities | Medium | Solve | |
| Redundant Connection | Medium | Solve | |
| Graph Valid Tree | Medium | Solve | |
| Is Graph Bipartite? | Medium | Solve |