DevPath

← All problems

Non-overlapping Intervals

Medium greedy · intervals

Description

Return the minimum number of intervals you must remove so the rest do not overlap.

Constraints

1 <= intervals <= 100000

Examples

Input: intervals = [[1,2],[2,3],[3,4],[1,3]]

Output: 1

Hints (1)
  • Sort by end time and keep the interval that finishes earliest.

Solutions

Sort by end, keep earliest finish. (requires "sort") · Time O(n log n) · Space O(1)

func eraseOverlapIntervals(intervals [][]int) int {
    sort.Slice(intervals, func(i, j int) bool { return intervals[i][1] < intervals[j][1] })
    removed, end := 0, -1<<62
    for _, iv := range intervals {
        if iv[0] < end {
            removed++
        } else {
            end = iv[1]
        }
    }
    return removed
}

Create a free account to submit solutions, track progress and save problems.

Create account