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
Count Unreachable Pairs: Connected Components01234Component 1: Size 2Component 2: Size 1Component 3: Size 2Unreachable Pairs Calculation:Comp1 × (Comp2 + Comp3) = 2 × (1 + 2) = 6Comp2 × Comp3 = 1 × 2 = 2Total: 6 + 2 = 8 unreachable pairs
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
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen