Non-overlapping Intervals

Greedy by earliest end — remove any interval that starts before the last kept end.

Medium
Time O(n log n) Space O(1)
LeetCode
2 min read
intervals greedy sorting

Problem#

Return the minimum number of intervals to remove so the rest are non-overlapping.

Examples#

  • [[1,2],[2,3],[3,4],[1,3]]1.
  • [[1,2],[1,2],[1,2]]2.

Constraints#

  • 1 <= intervals.length <= 10^5.

Approach#

Sort by end. Sweep, keeping any interval whose start ≥ last kept end. Drop the rest.

Solution#

Non-overlapping Intervals
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](auto& a, auto& b){ return a[1] < b[1]; });
int kept = 0, end = INT_MIN;
for (auto& it : intervals) {
if (it[0] >= end) { ++kept; end = it[1]; }
}
return intervals.size() - kept;
}
};

Editorial#

This is the classic interval scheduling problem. Sorting by end maximizes future flexibility: by keeping the interval that frees up the timeline soonest, we preserve the most room for subsequent intervals. The answer is total - kept.

Complexity#

  • Time: O(n log n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.