- Related Questions & Answers
- Minimum Size of Two Non-Overlapping Intervals in C++
- Merge Overlapping Intervals using C++.
- Random Point in Non-overlapping Rectangles in C++
- Maximum Sum of 3 Non-Overlapping Subarrays in C++
- Maximum Sum of Two Non-Overlapping Subarrays in C++
- Maximum sum two non-overlapping subarrays of given size in C++
- Max sum of M non-overlapping subarrays of size K in C++
- Program to find overlapping intervals and return them in ascending order in Python
- Count pairs of non-overlapping palindromic sub-strings of the given string in C++
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Program to find maximum sum of two non-overlapping sublists in Python
- Maximum sum of lengths of non-overlapping subarrays with k as the max element in C++
- Circle and Rectangle Overlapping in C++
- Maximal Disjoint Intervals in C++
- Remove Covered Intervals in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a collection of intervals; we have to find the minimum number of intervals we need to remove to make the rest of the intervals non-overlapping. So if the intervals are [[1,2], [2,3], [3,4], [1,3]], then the output will be 1, as we have to remove [1,3] to make all others are non-overlapping.

To solve this, we will follow these steps −

n := size of array

if n is 0, then return 0

count := 1

sort the array based on the end time of the intervals

end := end date of the first interval

for i in range 1 to n – 1

if start time of arr[i] >= end, then

end := end time of arr[i]

increase count by 1

return n – count

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; class Solution { public: static bool cmp(vector <int>& a, vector <int>& b){ return a[1] < b[1]; } int eraseOverlapIntervals(vector<vector<int>>& arr) { int n = arr.size(); if(!n)return 0; int cnt = 1; sort(arr.begin(), arr.end(), cmp); int end = arr[0][1]; for(int i = 1; i < n; i++){ if(arr[i][0] >= end){ end = arr[i][1]; cnt++; } } return n - cnt; } }; main(){ vector<vector<int>> v = {{1,2},{1,2},{1,2}}; Solution ob; cout << (ob.eraseOverlapIntervals(v)); }

[[1,2],[1,2],[1,2]]

2

Advertisements