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) means every point from a up to, but not including, b, remove each interval that is covered by another one. The interval [a, b) is covered by [c, d) when c ≤ a and b ≤ d. Return how many intervals remain.

Example 1
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: [3,6] lies inside [2,8].
Example 2
Input: intervals = [[1,4],[2,3]]
Output: 1
Solution

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.

The intervals of Example 1 sorted by start: [1, 4], [2, 8], [3, 6]. The farthest end so far is 4, then 8, then still 8. [3, 6] ends at 6, which is not past 8, so [2, 8] covers it.

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 maxEnd. An interval whose end is greater than maxEnd is kept: it is counted, and its end becomes the new maxEnd. Any other interval is covered, and maxEnd stays as it is.

Why one number is enough

Can an interval that gets past maxEnd still be covered? Not by one earlier in the sorted list, since all of those end before it does. Not by a later one either: a later interval either starts further right or, with the same start, is shorter because of the tie rule. And an interval that stays within maxEnd is covered by the one that set maxEnd, which started no later.

Java Solution

The method removeCoveredIntervals works in these steps:

  1. First, copy the array of intervals into sorted with intervals.clone(), so the caller's array keeps its order.
  2. Sort sorted with Arrays.sort and a comparator: smaller start first, and for equal starts, larger end first.
  3. Set the counter remaining to 0 and maxEnd to Integer.MIN_VALUE, a value below every end, so the first interval is always kept.
  4. Walk through sorted with one loop. When an interval's end is greater than maxEnd, add 1 to remaining and set maxEnd to that end. Otherwise the interval is covered and nothing changes.
  5. After the loop, return remaining.

The main method runs both examples, two intervals with the same start, a chain where each interval sits inside the one before, intervals that touch or stand apart, and a single interval.

Java
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:

Output
[[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 to 4, and [2, 3] ends at 3, inside it.

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 to 10 and the other two end inside it, so only 1 remains. In the fifth line, [1, 3] and [3, 5] meet at 3, but neither lies inside the other, so all three are kept.

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 sorted holds a reference to each of the n intervals, while the loop itself needs only remaining and maxEnd.

Sorting intervals by start is also the first step of Merge Intervals.