Remove Covered Intervals
Count the intervals that are left after removing every interval that lies inside another one.
Given a list of distinct intervals, where [a, b)ab[a, b)[c, d)c ≤ ab ≤ d
Example 1
Output: 2
Explanation: [3,6] lies inside [2,8].
Example 2
Output: 1
The Idea
Picture strips of tape laid along a ruler, each one marking a stretch from a start mark to an end mark. Some strips sit completely on top of a longer strip and add nothing that the longer one does not already mark. Those are the covered intervals, and the question is how many strips are left once they are peeled off.
In Example 1 the strips are [1, 4], [3, 6] and [2, 8]. The strip [3, 6] starts at 3, which is not before 2, and ends at 6, which is not after 8, so [2, 8] covers it. [1, 4] is not covered: it starts before both others. That leaves 2 intervals.
Checking every interval against every other one works, but it compares each pair. Is there a way to look at each interval just once? The order of the list is no help, so put the intervals in order by start: [1, 4], [2, 8], [3, 6]. Look at the picture below.
Sorted this way, every interval above the current one starts at or before it. So the start condition of covering already holds for all of them, and only the ends matter. In the column labelled "farthest end so far", [1, 4] sets it to 4 and [2, 8] raises it to 8, so both are kept. Then [3, 6] arrives, and its end 6 does not get past 8.
That is the key insight: after sorting by start, an interval is covered exactly when its end is no further right than the farthest end seen so far. The interval that set that farthest end, here [2, 8], is the one that covers it. A single number, kept up to date as we go down the list, replaces all the pairwise checks.
Solution Approach
Turning that idea into code starts with a look at the slow way of checking every pair. Then three things need settling: how to order intervals that share a start, what to remember while going down the sorted list, and why one number is enough.
Checking every pair
What does the slow way cost? For each interval, it tests all the others for one that covers it. With n intervals that is about n × n tests, so 1,000 intervals need about a million. Sorting takes about n log n steps, far fewer, and going down the sorted list afterwards is a single pass.
Ordering intervals with the same start
What if two intervals start at the same point, like [1, 2] and [1, 4]? The longer one, [1, 4], covers the shorter one. If [1, 2] came first, it would set the farthest end to 2, and then [1, 4] would raise it to 4, so both would be counted. Putting the longer interval first fixes this: [1, 4] sets the farthest end to 4, and [1, 2] then ends inside it.
So the sort compares starts first, smallest first, and when the starts are equal it compares ends, largest first.
The farthest end so far
What needs remembering while going down the list? Only the largest end among the intervals kept so far, in a variable named maxEndmaxEndmaxEndmaxEnd
Why one number is enough
Can an interval that gets past maxEndmaxEndmaxEnd
Java Solution
The method removeCoveredIntervals
- First, copy the array of intervals into
withsorted , so the caller's array keeps its order.intervals.clone() - Sort
withsorted and a comparator: smaller start first, and for equal starts, larger end first.Arrays.sort - Set the counter
to 0 andremaining tomaxEnd , a value below every end, so the first interval is always kept.Integer.MIN_VALUE - Walk through
with one loop. When an interval's end is greater thansorted , add 1 tomaxEnd and setremaining to that end. Otherwise the interval is covered and nothing changes.maxEnd - After the loop, return
.remaining
The main
import java.util.Arrays;
public class RemoveCoveredIntervals {
public static int removeCoveredIntervals(int[][] intervals) {
int[][] sorted = intervals.clone(); // leave the caller's array as it was
// Start ascending; for equal starts, the longer interval first.
Arrays.sort(sorted, (a, b) -> a[0] != b[0]
? Integer.compare(a[0], b[0])
: Integer.compare(b[1], a[1]));
int remaining = 0;
int maxEnd = Integer.MIN_VALUE; // below every end: the first one counts
for (int[] iv : sorted) {
if (iv[1] > maxEnd) { // reaches past everything before it
remaining++;
maxEnd = iv[1];
} // otherwise it is covered
}
return remaining;
}
static void show(int[][] intervals) {
System.out.println(Arrays.deepToString(intervals) + " -> "
+ removeCoveredIntervals(intervals));
}
public static void main(String[] args) {
show(new int[][] {{1, 4}, {3, 6}, {2, 8}});
show(new int[][] {{1, 4}, {2, 3}});
show(new int[][] {{1, 2}, {1, 4}}); // same start, shorter one first
show(new int[][] {{1, 10}, {2, 9}, {3, 8}}); // each inside the one before
show(new int[][] {{1, 3}, {3, 5}, {6, 7}}); // touching and apart
show(new int[][] {{5, 9}});
}
}
Running it prints:
[[1, 4], [3, 6], [2, 8]] -> 2
[[1, 4], [2, 3]] -> 1
[[1, 2], [1, 4]] -> 1
[[1, 10], [2, 9], [3, 8]] -> 1
[[1, 3], [3, 5], [6, 7]] -> 3
[[5, 9]] -> 1
Example 1 gives 2 and Example 2 gives 1, matching the expected answers. In Example 2, [1, 4] sets maxEnd
Look at the third line. The input lists [1, 2] before [1, 4], and the answer is 1, because the tie rule moves [1, 4] to the front. With a comparator that looks only at starts, Java's sort keeps equal starts in their input order, so [1, 2] stays first and the same input gives 2, the wrong answer.
In the fourth line, [1, 10] sets maxEnd
Complexity
Sorting takes most of the time, and the scan after it looks at each interval once.
- Time: O(n log n), because sorting the n intervals with the comparator dominates, while the loop afterwards makes a single comparison per interval.
- Space: O(n), because the copy in
holds a reference to each of the n intervals, while the loop itself needs onlysorted andremaining .maxEnd
Sorting intervals by start is also the first step of