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 INPUT 0 1 2 3 4 [1,2] [2,3] [3,4] [1,3] ^ Overlaps! intervals = [[1,2],[2,3], [3,4],[1,3]] 4 intervals total ALGORITHM STEPS 1 Sort by End Time [1,2],[2,3],[1,3],[3,4] 2 Initialize end = -inf, count = 0 3 Iterate Intervals Check if start >= end Interval | Overlap? | Action [1,2] | No | Keep, end=2 [2,3] | No | Keep, end=3 [1,3] | Yes | Remove +1 [3,4] | No | Keep, end=4 4 Return Count Removed intervals = 1 FINAL RESULT Non-overlapping Set: [1,2] [2,3] [3,4] [1,3] Removed Output: 1 OK - 1 removal needed Key Insight: Sorting by END time is crucial! By always keeping the interval that ends earliest, we leave maximum room for future intervals. This greedy choice minimizes removals. Time: O(n log n) for sorting | Space: O(1) extra space TutorialsPoint - Non-overlapping Intervals | Greedy - Sort by End Time
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