# Minimum number of edges to be removed from given Graph such that no path exists between given pairs of vertices

• Difficulty Level : Medium
• Last Updated : 14 Sep, 2021

Given an undirected graph consisting of N valued over the range [1, N] such that vertices (i, i + 1) are connected and an array arr[] consisting of M pair of integers, the task is to find the minimum number of edges that should be removed from the graph such that there doesn’t exist any path for every pair (u, v) in the array arr[].

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {{1, 4}, {2, 5}
Output: 1
Explanation:
For N = 5, the given graph can be represented as:

1 <-> 2 <-> 3 <-> 4 <-> 5

After removing the edge between vertices 2 and 3 or the edge between vertices 3 and 4, the graph modifies to:

1 <-> 2       3 <-> 4 <-> 5

Now, there doesn’t exist any path between every pair of nodes in the array. Therefore, the minimum number of edges that should be removed is 1.

Input: arr[] = {{1, 8}, {2, 7}, {3, 5}, {4, 6}, {7, 9}}
Output: 2

Approach: The given problem can be solved using a Greedy Approach. The idea is to sort the given array of pairs arr[] in increasing order of ending pairs and for each pair, say (u, v) remove the nearest edges connected to the vertex v so that all the other vertices on the connected components containing vertex v is unreachable. Follow the steps below to solve the given problem:

• Create a variable, say minEdges as 0, that stores the count of removed edges.
• Create a variable reachable as 0, that keeps track of the smallest vertex that is reachable from the last vertex i.e., N.
• Sort the given array of pairs arr[] in increasing order of the second value of the pairs.
• Traverse the given array arr[] and for every pair (u, v) in arr[], if reachable > u, it implies that there exists no path between u and v, otherwise removing the last edge between (v – 1) and v is the most optimal choice. Therefore, increment the value of minEdges by 1 and the value of reachable will be equal to v.
• After completing the above steps, print the value of minEdges as result.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Comparator function to sort the``// given array of pairs in increasing``// order of second value of the pairs``bool` `comp(pair<``int``, ``int``> a, pair<``int``, ``int``> b)``{``    ``if` `(a.second < b.second) {``        ``return` `true``;``    ``}``    ``return` `false``;``}` `// Function to find minimum number of edges``// to be removed such that there exist no``// path between each pair in the array arr[]``int` `findMinEdges(vector > arr,``                 ``int` `N)``{``    ``// Stores the count of edges to be deleted``    ``int` `minEdges = 0;` `    ``// Stores the smallest vertex rechable``    ``// from the current vertex``    ``int` `reachable = 0;` `    ``// Sort the array arr[] in increasing``    ``// order of the second value of the pair``    ``sort(arr.begin(), arr.end(), comp);` `    ``// Loop to iterate through array arr[]``    ``for` `(``int` `i = 0; i < arr.size(); i++) {` `        ``// If rechable > arr[i].first, there``        ``// exist no path between arr[i].first``        ``// and arr[i].second, hence continue``        ``if` `(reachable > arr[i].first)``            ``continue``;` `        ``else` `{``            ``// Update the rechable vertex``            ``reachable = arr[i].second;` `            ``// Increment minEdges by 1``            ``minEdges++;``        ``}``    ``}` `    ``// Return answer``    ``return` `minEdges;``}` `// Driver Code``int` `main()``{``    ``vector > arr = {``        ``{ 1, 8 }, { 2, 7 }, { 3, 5 }, { 4, 6 }, { 7, 9 }``    ``};``    ``int` `N = arr.size();``    ``cout << findMinEdges(arr, N);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.Arrays;` `class` `GFG``{``  ` `    ``// Comparator function to sort the``    ``// given array of pairs in increasing``    ``// order of second value of the pairs` `    ``// Function to find minimum number of edges``    ``// to be removed such that there exist no``    ``// path between each pair in the array arr[]``    ``public` `static` `int` `findMinEdges(``int``[][] arr, ``int` `N)``    ``{``      ` `        ``// Stores the count of edges to be deleted``        ``int` `minEdges = ``0``;` `        ``// Stores the smallest vertex rechable``        ``// from the current vertex``        ``int` `reachable = ``0``;` `        ``// Sort the array arr[] in increasing``        ``// order of the second value of the pair``        ``Arrays.sort(arr, (a, b) -> (a[``1``] - b[``1``]));` `        ``// Loop to iterate through array arr[]``        ``for` `(``int` `i = ``0``; i < arr.length; i++) {` `            ``// If rechable > arr[i], there``            ``// exist no path between arr[i]``            ``// and arr[i], hence continue``            ``if` `(reachable > arr[i][``0``])``                ``continue``;` `            ``else` `{``                ``// Update the rechable vertex``                ``reachable = arr[i][``1``];` `                ``// Increment minEdges by 1``                ``minEdges++;``            ``}``        ``}` `        ``// Return answer``        ``return` `minEdges;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String args[]) {``        ``int``[][] arr = { { ``1``, ``8` `}, { ``2``, ``7` `}, { ``3``, ``5` `}, { ``4``, ``6` `}, { ``7``, ``9` `} };``        ``int` `N = arr.length;``        ``System.out.println(findMinEdges(arr, N));``    ``}``}` `// This code is contributed by _saurabh_jaiswal.`

## Python3

 `# Python 3 program for the above approach` `# Comparator function to sort the``# given array of pairs in increasing``# order of second value of the pairs`  `# Function to find minimum number of edges``# to be removed such that there exist no``# path between each pair in the array arr[]``def` `findMinEdges(arr, N):``    ``# Stores the count of edges to be deleted``    ``minEdges ``=` `0` `    ``# Stores the smallest vertex rechable``    ``# from the current vertex``    ``reachable ``=` `0` `    ``# Sort the array arr[] in increasing``    ``# order of the second value of the pair``    ``arr.sort()` `    ``# Loop to iterate through array arr[]``    ``for` `i ``in` `range``(``len``(arr)):``        ``# If rechable > arr[i].first, there``        ``# exist no path between arr[i].first``        ``# and arr[i].second, hence continue``        ``if` `(reachable > arr[i][``0``]):``            ``continue` `        ``else``:``            ``# Update the rechable vertex``            ``reachable ``=` `arr[i][``1``]` `            ``# Increment minEdges by 1``            ``minEdges ``+``=` `1` `    ``# Return answer``    ``return` `minEdges``+``1` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=` `[[``1``, ``8``],[``2``, ``7``],[``3``, ``5``],[``4``, ``6``],[``7``, ``9``]]``    ``N ``=` `len``(arr)``    ``print``(findMinEdges(arr, N))``    ` `    ``# This code is contributed by SURENDRA_GANGWAR.`

## Javascript

 ``
Output:
`2`

Time Complexity: O(M*log M)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up