# Minimum removals required to make ranges non-overlapping

Given a list of ranges with starting and end value, the task is to find the minimum number of ranges that are required to be removed to make remaining ranges non-overlapping.

Examples:

Input : input = {{1, 2}, {4, 7}, {3, 8}}
Output : 1
Explanation: Removal of {3, 8} makes {{1, 2} and {4, 7}} non-overlapping.

Input : input = {{ 10, 20 }, { 10, 20 } , { 10, 20 }}
Output : 2
Explanation: Removal of [10, 20] makes the remaining ranges non-overlapping.

Input : input = {{1, 2}, {5, 10}, {18, 35}, {40, 45}}
Output : 0
Explanation:All ranges are already non-overlapping.

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

Approach:

• Sort the ranges by their starting values.
• Traverse through the ranges and check if any range has a starting point less than the ending point of the previous (ie. there is an overlap).
• Remove the range with greater ending point.
• Below code is the implementation of the above approach:

 `#include ` `using` `namespace` `std; ` ` `  `int` `minRemovals(vector >& ranges) ` `{ ` ` `  `    ``int` `size = ranges.size(), rem = 0; ` ` `  `    ``if` `(size <= 1) ` `        ``return` `0; ` ` `  `    ``// Sort by minimum starting point ` `    ``sort(ranges.begin(), ranges.end(),  ` `        ``[](``const` `vector<``int``>& a, ``const` `vector<``int``>& b)  ` `                    ``{ ``return` `a[0] < b[0]; }); ` ` `  `    ``int` `end = ranges[0][1]; ` `    ``for` `(``int` `i = 1; i < ranges.size(); i++) { ` ` `  `        ``// If the current starting point is less than ` `        ``// the previous interval's ending point  ` `        ``// (ie. there is an overlap) ` `        ``if` `(ranges[i][0] < end) { ` `            ``// increase rem ` `            ``rem++; ` `            ``// Remove the interval ` `            ``// with the higher ending point ` `            ``end = min(ranges[i][1], end); ` `        ``} ` `        ``else` `            ``end = ranges[i][1]; ` `    ``} ` ` `  `    ``return` `rem; ` `} ` ` `  `// Driver code ` `int` `main() ` `{ ` `    ``vector > input = { { 19, 25 },  ` `                        ``{ 10, 20 }, { 16, 20 } }; ` `    ``cout << minRemovals(input) << endl; ` `} `

Output:

```2
```

Time Complexity: O(n log n)

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.