Skip to main content

Non-overlapping Intervals

Medium
Data Structures and Algorithms
Editorial
Topics:
Array
Greedy
Sorting

You are given intervals, where each element is an interval represented by two integers [start, end]. An interval covers the positions from start through end; two intervals overlap when they share any interior portion. Intervals that meet exactly at an endpoint do not overlap.

Remove as few intervals as possible so that every pair of remaining intervals is non-overlapping. Return the minimum number of intervals that must be removed.

Example 1:

Input: intervals = [[1,3],[3,6],[6,10]]
Output: 0
Explanation: Each interval only touches the next one at an endpoint, so none of them overlap.

Example 2:

Input: intervals = [[1,4],[2,3],[5,7],[6,8]]
Output: 2
Explanation: One interval must be removed from each overlapping pair of groups; for instance, keep [2,3] and [5,7].

Example 3:

Input: intervals = [[1,10],[2,4],[3,7],[8,9]]
Output: 2
Explanation: The interval [1,10] overlaps all three shorter intervals, and [2,4] overlaps [3,7]. Removing [1,10] and either one of [2,4] or [3,7] leaves a non-overlapping set.

Constraints:

  • 1 <= intervals.length <= 10^5
  • Each element of intervals contains exactly 2 integers.
  • For every interval [start, end], start < end.
  • 1 <= start <= 5 * 10^4.
  • 1 <= end <= 5 * 10^4.

Need help or want more practice?

Practise in an interviewGet AI Coach help