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.
1#include <vector>
2#include <algorithm>
3
4using namespace std;
5
6int removeCoveredIntervals(vector<vector<int>>& intervals) {
7 sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) {
8 return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0];
9 });
10 int remaining = 0, prevEnd = 0;
11 for (const auto& interval : intervals) {
12 if (interval[1] > prevEnd) {
13 remaining++;
14 prevEnd = interval[1];
15 }
16 }
17 return remaining;
18}
The C++ implementation uses std::sort
with a lambda function to sort by start and then by end in descending order when starts are equal. As it iterates through the intervals, it checks if an interval's end is greater than the current tracked maximum, signifying it is not covered.
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.
Java iteration uses two-loop construct to simulate graph edge relation. It deploys an array of boolean type to make coverage marks and appropriately decrease the counter for retained intervals.