Home
DSA Patterns
Intervals
Non-overlapping Intervals
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
See how sorting by End Time allows us to reliably pick the 'best' intervals to keep.
Dry Run
Input: [[1,2], [2,3], [3,4], [1,3]]
| Step | Interval | End Time | Decision | Count |
|---|---|---|---|---|
| Init | - | - | Sort by End: [[1,2], [2,3], [1,3], [3,4]] |
0 |
| 1 | [1,2] |
2 | Keep. prevEnd = 2. |
0 |
| 2 | [2,3] |
3 | Start 2 >= prev 2. Keep. prevEnd = 3. |
0 |
| 3 | [1,3] |
3 | Start 1 < prev 3. Overlap! Remove. |
1 |
| 4 | [3,4] |
4 | Start 3 >= prev 3. Keep. prevEnd = 4. |
1 |
Edge Cases & Common Mistakes
- Equal End Times: The sort order for same end times doesn't affect correctness for count, though sorting by start (secondary) produces consistent selection.
- Touching Intervals:
[1,2]and[2,3]do NOT overlap. Logic must use>=. - Negative Numbers: Intervals can have negative coordinates.
Solution
Greedy optimization O(N log N).
Non-overlapping Intervals Code
1var eraseOverlapIntervals = function(intervals) {2 if (!intervals.length) return 0;3 intervals.sort((a, b) => a[1] - b[1]);45 let count = 0;6 let prevEnd = intervals[0][1];78 for (let i = 1; i < intervals.length; i++) {9 if (intervals[i][0] >= prevEnd) {10 prevEnd = intervals[i][1];11 } else {12 count++;13 }14 }15 return count;16};
