Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Each interval is defined as a pair of integers [start, end]
, representing the start and end times.
[start, end]
where start <= end
.1
to 1000
.The problem can be approached by sorting the intervals based on their ending times. Here’s why this strategy works:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int eraseOverlapIntervals(vector<pair<int, int>>& intervals) {
if (intervals.empty()) return 0;
// Sort intervals based on their end times
sort(intervals.begin(), intervals.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second < b.second;
});
int removals = 0; // Counter for the number of intervals to remove
int prev_end = intervals[0].second; // End time of the last added interval
for (int i = 1; i < intervals.size(); ++i) {
if (intervals[i].first < prev_end) {
// If there is an overlap
removals++;
} else {
// No overlap, update the end time of the last added interval
prev_end = intervals[i].second;
}
}
return removals;
}
int main() {
// Example usage
vector<pair<int, int>> intervals = \{\{1, 2}, {2, 3}, {3, 4}, {1, 3}};
cout << "Minimum number of intervals to remove: " << eraseOverlapIntervals(intervals) << endl;
return 0;
}
The time complexity of this solution is (O(n \log n)), where (n) is the number of intervals. This is due to the sorting step. The subsequent iteration through the intervals is (O(n)), making the overall complexity (O(n \log n)).
Together, these result in (O(n \log n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?