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 of Nodes INPUT Undirected Graph (n=3) 0 1 2 n = 3 edges = [[0,1],[0,2],[1,2]] All nodes connected 3 edges forming a triangle Every node reachable from every other node ALGORITHM STEPS 1 Build Adjacency List Create graph representation 0: [1, 2] 1: [0, 2] 2: [0, 1] 2 DFS to Find Components Explore all connected nodes Start DFS from node 0 Visit: 0 --> 1 --> 2 (size=3) 3 Store Component Sizes Record size of each component Components: [3] (only 1) 4 Count Unreachable Pairs size_i * (remaining nodes) 1 component = 0 unreachable FINAL RESULT Single Connected Component Component 1 0 1 2 Output 0 All nodes connected! No unreachable pairs OK Pairs formula: sum(c_i * remaining) Key Insight: Use DFS to find connected components. For each component of size S, it contributes S * (n - S) unreachable pairs with nodes outside it. Sum across all components, then divide by 2 (each pair counted twice). Time: O(n + edges) | Space: O(n + edges) for adjacency list and visited array TutorialsPoint - Count Unreachable Pairs of Nodes in an Undirected Graph | DFS Connected Components Approach
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