Count Unreachable Pairs of Nodes in an Undirected Graph - 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.
Two nodes are unreachable from each other if there is no path connecting them in the graph.
Input & Output
Example 1 — Basic Connected Components
$
Input:
n = 3, edges = [[0,1],[0,2],[1,2]]
›
Output:
0
💡 Note:
All nodes are connected through edges. Node 0 connects to 1 and 2, creating one big component of size 3. Since all nodes can reach each other, there are 0 unreachable pairs.
Example 2 — Multiple Components
$
Input:
n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
›
Output:
14
💡 Note:
Component 1: {0,2,4,5} (size 4), Component 2: {1,6} (size 2), Component 3: {3} (size 1). Unreachable pairs: 4×3 + 2×1 = 12 + 2 = 14.
Example 3 — No Edges
$
Input:
n = 3, edges = []
›
Output:
3
💡 Note:
No edges means each node is its own component. Pairs: (0,1), (0,2), (1,2) = 3 unreachable pairs total.
Constraints
- 1 ≤ n ≤ 105
- 0 ≤ edges.length ≤ 2 × 105
- edges[i].length == 2
- 0 ≤ ai, bi < n
- ai ≠ bi
- There are no repeated edges
Visualization
Tap to expand
Understanding the Visualization
1
Input Graph
n=5 nodes with edges connecting some pairs
2
Find Components
Group nodes that can reach each other
3
Count Pairs
Multiply sizes of different components
Key Takeaway
🎯 Key Insight: Nodes in different connected components can never reach each other
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code