Given a graph consisting of N nodes numbered from 0 to N – 1 and M edges in the form of pairs {a, b}, the task is to find the minimum number of edges to be added to the graph such that if there exists a path from any node a to node b, then there should be paths from node a to nodes [ a + 1, a + 2, a + 3, …, b – 1] as well.

Examples:

Input:_ N = 7, M = 3, Edges[][] = {{1, 5}, {2, 4}, {3, 4}} _

Output:_ 1 _

Explanation:

_There is a path from 1 to 5. So there should be paths from 1 to 2, 3 and 4 as well. _

Adding an edge {1, 2} will be sufficient to reach the other two nodes of the graph.

Input:_ N = 8, M = 3 Edges[][] = {{1, 2}, {2, 3}, {3, 4}} _

Output:_ 0 _

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:

The idea is to use a Disjoint Set or Union find. Each component in the disjoint set should have consecutive nodes. This can be done by maintaining maximum_node[] and minimum_node[] arrays to store the maximum and minimum value of nodes in each component respectively. Follow the steps below to solve the problem:

  • Create a structure for the disjoint set union.
  • Initialize the answer as 0 and iterate over all the nodes in the graph to get the component of the current node.

#data structures #graph #disjoint-set #union-find #data analysis

Minimum number of Edges to be added to a Graph
1.45 GEEK