Leetcode #2316: Count Unreachable Pairs of Nodes in an Undirected Graph
In this guide, we solve Leetcode #2316 Count Unreachable Pairs of Nodes in an Undirected Graph in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Depth-First Search, Breadth-First Search, Union Find, Graph
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
Example
Input: n = 3, edges = [[0,1],[0,2],[1,2]]
Output: 0
Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.
Python Solution
class Solution:
def countPairs(self, n: int, edges: List[List[int]]) -> int:
def dfs(i: int) -> int:
if vis[i]:
return 0
vis[i] = True
return 1 + sum(dfs(j) for j in g[i])
g = [[] for _ in range(n)]
for a, b in edges:
g[a].append(b)
g[b].append(a)
vis = [False] * n
ans = s = 0
for i in range(n):
t = dfs(i)
ans += s * t
s += t
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.