#2316

Count Unreachable Pairs of Nodes in an Undirected Graph

Medium
Depth-First SearchBreadth-First SearchUnion-FindGraph TheoryDepth-First Search (DFS)Breadth-First Search (BFS)Graph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + e)
Space
O(1)
O(n)
💡

Intuition

Time O(n + e)Space O(n)

The optimal approach uses the concept of connected components in the graph. By finding the size of each connected component, we can calculate the number of unreachable pairs efficiently without checking every pair individually.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create an adjacency list from the edges.
  2. 2Step 2: Use DFS or BFS to find all connected components and their sizes.
  3. 3Step 3: Calculate the total number of pairs using the sizes of the components: for each component size, calculate pairs with nodes in other components.
solution.py36 lines
1# Full working Python code
2from collections import defaultdict
3
4def count_unreachable_pairs(n, edges):
5    graph = defaultdict(list)
6    for a, b in edges:
7        graph[a].append(b)
8        graph[b].append(a)
9
10    visited = [False] * n
11    component_sizes = []
12
13    def dfs(node):
14        stack = [node]
15        size = 0
16        while stack:
17            curr = stack.pop()
18            if not visited[curr]:
19                visited[curr] = True
20                size += 1
21                stack.extend(graph[curr])
22        return size
23
24    for i in range(n):
25        if not visited[i]:
26            size = dfs(i)
27            component_sizes.append(size)
28
29    total_pairs = 0
30    total_nodes = 0
31    for size in component_sizes:
32        total_pairs += size * total_nodes
33        total_nodes += size
34
35    return total_pairs
36

Complexity note: The time complexity is O(n + e) where e is the number of edges, as we traverse each node and edge once. The space complexity is O(n) for the graph representation and visited array.

  • 1Understanding connected components is crucial for solving graph-related problems.
  • 2Using efficient traversal methods (DFS/BFS) can significantly reduce time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.