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
Non-overlapping Intervals: Find Minimum RemovalsInput: [[1,2],[2,3],[3,4],[1,3]][1,2][2,3][3,4][1,3] OVERLAPS1234After Greedy Selection (sort by end time):Keep: [1,2] (ends at 2)Keep: [2,3] (ends at 3, starts at 2 ≥ 2)Keep: [3,4] (ends at 4, starts at 3 ≥ 3)Remove: [1,3] (overlaps with [1,2])Remove 1 interval
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
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
89.4K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen