Data Structures19 sections · 729 units
Open in Course

Non-overlapping Solution

Greedy removal

Find max non-overlapping, then removals = total - max.

function eraseOverlapIntervals(intervals)
    sort intervals by end time
    kept := 0
    lastEnd := -infinity

    for interval in intervals
        if interval.start >= lastEnd then
            kept := kept + 1
            lastEnd := interval.end

    return length(intervals) - kept

Alternatively, count how many times we skip an interval:

When a new interval overlaps the previous, remove the one ending later (keep the one ending earlier to maximize future options).

Time: O(nlogn)O(n \log n). Space: O(1)O(1).