Count Unreachable Pairs of Nodes in an Undirected Graph Problem
Problem
You are given an integer n
. There is an undirected graph with n
nodes, numbered from 0
to n - 1
. You are given a 2D integer array edges
where edges[i] = [ai, bi]
denotes that there exists an undirected edge connecting nodes ai
and bi
.
Return the number of pairs of different nodes that are unreachable from each other.
Examples
Example 1:
|
|
Example 2:
|
|
Therefore, we return 14.
Constraints:
1 <= n <= 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ai, bi < n
ai != bi
- There are no repeated edges.
Solution
Method 1 – Connected Components (DFS/Union-Find) (1)
Intuition
The key idea is that nodes in the same connected component can reach each other, but nodes in different components cannot. So, for each component, count its size, and the number of unreachable pairs is the sum over all pairs of nodes in different components.
Approach
- Build the graph from the edge list.
- Use DFS or Union-Find to find all connected components and their sizes.
- For each component of size s, the number of unreachable pairs contributed is s * (total_nodes_remaining - s).
- Accumulate the answer as you process each component.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + m)
, where n is the number of nodes and m is the number of edges; each node and edge is visited once. - 🧺 Space complexity:
O(n + m)
, for the adjacency list and visited array.