Count Unreachable Pairs of Nodes in an Undirected Graph

Given n nodes and an undirected edge list, return the number of unordered node pairs that cannot reach each other. DSU component sizes are the key ingredient here: once each component size is known, unreachable pairs are counted across components.

Input Format

n = number of nodes, edges = undirected edges

Output Format

number of unreachable unordered pairs

Constraints

  • 1 <= input size <= 10^5
  • -10^9 <= numeric values <= 10^9
  • Input must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

n = 5
edges = [[0,1],[2,3],[0,4]]

Output:

6

Explanation:

Component sizes are 3 and 2, so unreachable pairs = 3 × 2 = 6.

Example 2:

Input:

n = 3
edges = [[0,1]]

Output:

2

Example 3:

Input:

n = 4
edges = [[0,1],[1,2],[2,3]]

Output:

0

Explanation:

The graph is fully connected.

Loading...
Count Unreachable Pairs of Nodes in an…