Sponsored
Sponsored
First, sort the intervals by their starting point. If two intervals have the same start, sort them by their ending point in descending order. This helps in ensuring that when you iterate, you can simply keep a check on the maximum end encountered and compare each interval to determine if it is covered.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) since sorting is done in place.
1def removeCoveredIntervals(intervals):
2 intervals.sort(key=lambda x: (x[0], -x[1]))
3 remaining = 0
4 prev_end = 0
5 for _, end in intervals:
6 if end > prev_end:
7 remaining += 1
8 prev_end = end
9 return remaining
In Python, sorting is done using the sort()
method with a custom key that first checks the starting point and then the ending point in descending order if starts are equal. The counting mechanism is similar to the previous implementations, keeping a count of uncovered intervals.
Conceptually, treat each pair of intervals as a directed edge if one interval is covering another. Such implicit graph construction helps identify covered intervals. You process over this graph to recognize unique intervals not covered by others. This approach may be non-trivial compared to the sorting technique, but it provides a different perspective.
Time Complexity: O(n^2) for comparing each interval with every other one.
Space Complexity: O(n) for the boolean array tracking covered intervals.
using namespace std;
bool isCovered(const vector<int>& a, const vector<int>& b) {
return b[0] <= a[0] && a[1] <= b[1];
}
int removeCoveredIntervalsGraph(vector<vector<int>>& intervals) {
int remaining = intervals.size();
vector<bool> covered(intervals.size(), false);
for (int i = 0; i < intervals.size(); ++i) {
for (int j = 0; j < intervals.size(); ++j) {
if (i != j && !covered[i] && isCovered(intervals[i], intervals[j])) {
covered[i] = true;
--remaining;
break;
}
}
}
return remaining;
}
C++ adopts a similar checking mechanism through nested loops to model the coverage relationship graph. Boolean vector 'covered' facilitates tracking and remaining count decrements for each interval detected as covered.