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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int RemoveCoveredIntervals(int[][] intervals) {
6 Array.Sort(intervals, (a, b) => a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
7 int remaining = 0, prevEnd = 0;
8 foreach (var interval in intervals) {
9 if (interval[1] > prevEnd) {
10 remaining++;
11 prevEnd = interval[1];
12 }
13 }
14 return remaining;
15 }
16}
C# implementation uses Array.Sort()
and defines a comparator lambda to organize intervals as per the requirement: Start ascending and End descending. The removal and counting logic follows the pattern seen in the other implementations.
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
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.