Command Palette
Search for a command to run...
Problem 15.5 · IntervalsMedium
What it teaches: Activity selection: sort by end, keep every interval compatible with the last kept, and remove the rest.
Practise it on judges as “Non-overlapping Intervals”.
The problem
Return the minimum number of intervals to remove so the rest don't overlap. Intervals that only touch (like [1,2] and [2,3]) don't overlap.
Example 1
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Example 2
Input: [[1,2],[1,2],[1,2]]
Output: 2
Constraints
Pattern clues in the wording
- → Keep the most intervals without overlap
- → Greedy by earliest end
These clues point to Greedy Choice: Make the best-looking choice at each step and never undo it, after proving that this choice is always safe.
Stuck? Take one hint at a time
Solution.java · starterimport java.util.*;
class Solution {
public int eraseOverlapIntervals(int[][] intervals) {
return 0;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Test cases
| # | Input | Expected |
|---|
| 1 | intervals = [[1,2],[2,3],[3,4],[1,3]] | 1 |
| 2 | intervals = [[1,2],[1,2],[1,2]] | 2 |
| 3 | intervals = [[1,2],[2,3]] | 0 |
+ 1 hidden test the code runner will check