Leetcode 2316: Count Unreachable Pairs of Nodes in an Undirected Graph

grid47
grid47
Exploring patterns and algorithms
Mar 20, 2024 7 min read

You are given an undirected graph with n nodes and a list of edges connecting the nodes. The goal is to find the number of pairs of distinct nodes that are unreachable from each other.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer n representing the number of nodes, followed by a list of edges where each edge is a pair of integers representing nodes connected by an edge.
Example: n = 4, edges = [[0,1],[1,2],[2,3]]
Constraints:
• 1 <= n <= 10^5
• 0 <= edges.length <= 2 * 10^5
• Each edge connects two different nodes, and there are no repeated edges.
Output: Return the number of pairs of distinct nodes that are unreachable from each other.
Example: For n = 7 and edges = [[0,2],[0,5],[2,4],[1,6],[5,4]], the output is 14.
Constraints:
• The output should be a non-negative integer.
Goal: The goal is to compute the number of unreachable pairs by finding the connected components in the graph and calculating how many pairs exist between nodes that do not belong to the same component.
Steps:
• 1. Build an adjacency list representation of the graph.
• 2. Perform a DFS or BFS to find all connected components.
• 3. For each connected component, calculate the number of unreachable pairs.
• 4. Subtract the reachable pairs from the total possible pairs (n * (n-1) / 2).
Goal: The problem constraints are as follows:
Steps:
• 1 <= n <= 10^5
• 0 <= edges.length <= 2 * 10^5
• Each edge connects two different nodes, and there are no repeated edges.
• The number of edges will not exceed the maximum possible number of edges.
Assumptions:
• The graph is undirected.
• The nodes are numbered from 0 to n-1.
Input: n = 4, edges = [[0,1],[1,2],[2,3]]
Explanation: In this example, all nodes are connected, so there are no unreachable pairs. Hence, the output is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus