FAANGPrep Sprint
Non-overlapping Intervals
Find the minimum number of intervals to remove to eliminate all overlaps.
Problem Understanding
Each entry of intervals is a pair [start, end]. Return the fewest intervals you have to delete so that none of the remaining ones overlap. Intervals that only touch at an endpoint, like [1,2] and [2,3], do not count as overlapping.
Example 1:
- Input:
[[1,2],[2,3],[3,4],[1,3]] - Output:
1 - Explanation: Remove
[1,3]to handle the overlaps with[1,2]and[2,3].
Algorithm Strategy
This is a classic Greedy problem. Removing as few intervals as possible is the same as keeping as many as possible, and the interval that finishes earliest leaves the most room for everything after it.
- Sort by End Time: Sort intervals by
endascending. - Keep the first: It ends earliest, so keep it and set
prevEndto its end. - Check each later interval
curr:- If
curr.start >= prevEnd, it does not overlap the last kept interval: keep it and setprevEnd = curr.end. - Otherwise it overlaps. Because of the sort,
currends no earlier than the interval already kept, so keeping that one never leaves less room: removecurrand add 1 to the count.
- If
- Return the count.
Interactive Visualization
4 INTERVALS
INPUT
intervals · as given
[1,2]
[2,3]
[3,4]
[1,3]
1
4
prevEnd
—
Kept
0
Removed
0
4 intervals: remove as few as possible so none overlap
Next
Sort by end time: [[1,2], [2,3], [1,3], [3,4]] — the interval that finishes first leaves the most room
Intervals
See how sorting by End Time allows us to reliably pick the 'best' intervals to keep.
