Count Unreachable Pairs of Nodes in an Undirected Graph - Problem
Imagine you have n islands numbered from 0 to n-1, and some islands are connected by bridges. Your task is to find how many pairs of islands cannot reach each other through any path of bridges.
You're given:
- n: The total number of islands (nodes)
- edges: A 2D array where
edges[i] = [a, b]means there's a bridge connecting islandsaandb
Goal: Return the number of pairs of different islands that are unreachable from each other.
Example: If you have islands [0, 1, 2] where 0-1 are connected but 2 is isolated, then pairs (0,2) and (1,2) are unreachable from each other, so the answer is 2.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 3, edges = [[0,1]]
โบ
Output:
2
๐ก Note:
Nodes 0 and 1 are connected, but node 2 is isolated. The unreachable pairs are (0,2) and (1,2), so the answer is 2.
example_2.py โ 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ร2 + 4ร1 + 2ร1 = 8 + 4 + 2 = 14.
example_3.py โ All Connected
$
Input:
n = 3, edges = [[0,1],[1,2]]
โบ
Output:
0
๐ก Note:
All nodes are in one connected component, so every pair is reachable. No unreachable pairs exist.
Constraints
- 1 โค n โค 105
- 0 โค edges.length โค 2 ร 105
- edges[i].length == 2
- 0 โค ai, bi < n
- ai != bi
- No duplicate edges
Visualization
Tap to expand
Understanding the Visualization
1
Map the Network
Build adjacency list from edges to represent ferry connections
2
Find Island Groups
Use DFS to discover all connected components (groups of reachable islands)
3
Count Group Sizes
Record the size of each connected component
4
Calculate Unreachable Pairs
Multiply sizes between different groups: if groups have sizes [a,b,c], unreachable pairs = aรb + aรc + bรc
Key Takeaway
๐ฏ Key Insight: Transform the problem from checking every pair O(nยฒ) to finding connected components O(V+E) and using multiplication to count unreachable pairs between different components.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code