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.
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.
Time & Space Complexity
Time Complexity
O(V + E)
Visit each vertex and edge exactly once during DFS traversal
ā Linear Growth
Space Complexity
O(V + E)
Adjacency list storage + DFS recursion stack + visited array
ā Linear Space
Constraints
- 1 ⤠n ⤠105
- 0 ⤠edges.length ⤠2 à 105
- edges[i].length == 2
- 0 ⤠ai, bi < n
- ai != bi
- No duplicate edges
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code