AlgoInsight

DSA problem

Remove Covered Intervals

MediumIntervalsPattern: Intervalstop600GoogleAmazonMicrosoftAdobeBloomberg

Given an array intervals where intervals[i] = [l_i, r_i] represents the inclusive interval [l_i, r_i], remove all intervals that are covered by another interval in the list. The interval [a, b] is covered by [c, d] if and only if c <= a and b <= d. Return the number of remaining intervals after removing all covered intervals.

A first instinct is to check every pair of intervals for coverage, costing O(n^2). Sorting transforms the problem into an O(n log n) sweep that visits each interval just once. The right sort order is the key insight: sort by start ascending, and when starts tie, by end descending.

Why that tie-breaker? After sorting by start ascending, any interval that comes later has a start at least as large as the previous one, so its left endpoint is never to the left of an earlier interval. Equal starts complicate the picture because if two intervals share the same start, the shorter one is covered by the longer one. Putting the longer (larger end) first ensures the shorter ones come after and will be detected as covered.

The optimal algorithm sweeps once tracking the maximum end seen so far. For each new interval, if its end is strictly greater than the running max end, the interval is not covered (it extends past everything before it), so increment the count and update the max end. Otherwise the interval is covered and is silently skipped. Return the count of kept intervals.

Examples

Example 1
Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Sorted by (start asc, end desc) gives [[1,4],[2,8],[3,6]]. Keep [1,4] (max end = 4). [2,8] has end 8 > 4, keep (max end = 8). [3,6] has end 6 <= 8, covered. Answer = 2.
Example 2
Input: intervals = [[1,4],[2,3]]
Output: 1
Explanation: After sorting (start asc, end desc): [[1,4],[2,3]]. Keep [1,4] (max end = 4). [2,3] has end 3 <= 4, covered. Answer = 1.
Example 3
Input: intervals = [[0,10],[5,12]]
Output: 2
Explanation: Neither interval covers the other: [0,10] does not contain [5,12] (since 12 > 10), and [5,12] starts later than [0,10]. Both are kept.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arrayintervalssorting

Browse all DSA problems