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 <stdio.h>
2#include <stdlib.h>
3
4int compare(const void *a, const void *b) {
5 int *intA = *(int**)a;
6 int *intB = *(int**)b;
7 if (intA[0] != intB[0])
8 return intA[0] - intB[0];
9 return intB[1] - intA[1];
10}
11
12int removeCoveredIntervals(int** intervals, int intervalsSize, int* intervalsColSize) {
13 qsort(intervals, intervalsSize, sizeof(intervals[0]), compare);
14 int remaining = 0, prevEnd = 0;
15 for (int i = 0; i < intervalsSize; ++i) {
16 if (intervals[i][1] > prevEnd) {
17 remaining++;
18 prevEnd = intervals[i][1];
19 }
20 }
21 return remaining;
22}
This C solution includes sorting the 2D array of intervals based on custom rules as mentioned. After sorting, it iterates through each interval, and incrementally counts those that are not covered by keeping a check on the last maximum end encountered.
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.
1
JavaScript's approach simulates viewing comparing pairs as potential edges, denoting coverage. The 'covered' list matches intervals owing to structural covering, decrementing the result variable for any intervals that should be considered 'covered'.