Non-overlapping Intervals - Problem
Given an array of intervals intervals where intervals[i] = [start_i, end_i], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note that intervals which only touch at a point are non-overlapping. For example, [1, 2] and [2, 3] are non-overlapping.
Input & Output
Example 1 — Basic Overlap
$
Input:
intervals = [[1,2],[2,3],[3,4],[1,3]]
›
Output:
1
💡 Note:
After sorting by end time: [[1,2],[2,3],[1,3],[3,4]]. Keep [1,2], [2,3], [3,4]. Remove [1,3] which overlaps with [1,2].
Example 2 — Multiple Overlaps
$
Input:
intervals = [[1,2],[1,2],[1,2]]
›
Output:
2
💡 Note:
All three intervals are identical and overlap. We can only keep one, so remove 2 intervals.
Example 3 — No Overlaps Needed
$
Input:
intervals = [[1,2],[2,3]]
›
Output:
0
💡 Note:
Intervals [1,2] and [2,3] only touch at point 2, which is considered non-overlapping. No removal needed.
Constraints
- 1 ≤ intervals.length ≤ 105
- intervals[i].length == 2
- -5 × 104 ≤ starti < endi ≤ 5 × 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of intervals with potential overlaps
2
Process
Sort by end time and apply greedy selection
3
Output
Minimum number of intervals to remove
Key Takeaway
🎯 Key Insight: Sort by end time and greedily keep intervals that end earliest to maximize non-overlapping selections
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code