Non-overlapping Intervals

Medium
Intervals

Given an array of 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.

Key insight: This is a greedy problem. Sort by END time, not start time. Always keep the interval that ends earliest, as it leaves the most room for future intervals.

Why sort by end time? Consider intervals [1,10] and [2,3]. If we keep [1,10], we might have to remove many other intervals. But if we keep [2,3], we have more room for subsequent intervals.

Real-world analogy: Imagine you're scheduling as many activities as possible in a day. You'd prioritize activities that end earlier, giving you more time for others.

Example 1

Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] overlaps with [1,2] and [2,3]. Remove [1,3] to make the rest non-overlapping.

Example 2

Input: intervals = [[1,2],[1,2],[1,2]]
Output: 2
Explanation: All three intervals are identical. We need to remove 2 of them.

Example 3

Input: intervals = [[1,2],[2,3]]
Output: 0
Explanation: These intervals share only a boundary point. They are considered non-overlapping.

Constraints

  • 1 <= intervals.length <= 10^5
  • intervals[i].length == 2
  • -5 * 10^4 <= start_i < end_i <= 5 * 10^4
Show Hints (4)
Hint 1: Think about this as an interval scheduling problem - which intervals should we keep?
Hint 2: What if we sorted by end time instead of start time?
Hint 3: Greedy approach: always keep the interval that ends earliest.
Hint 4: Count intervals that overlap with the previously kept interval.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?