Intervals
Medium
Non-overlapping Intervals
Find the minimum number of intervals to remove to eliminate all overlaps.
10 min read
Solve on LeetCodeProblem Understanding
Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
- Input:
[[1,2],[2,3],[3,4],[1,3]] - Output:
1 - Explanation: Remove
[1,3]to handle the overlaps with[1,2]and[2,3].
Algorithm Strategy
This is a classic Greedy problem. To minimize removed intervals (or maximize kept ones), we should prioritize intervals that finish early. This leaves the maximum room for subsequent intervals.
- Sort by End Time: Sort intervals by
endtime ascending. - Iterate: Keep track of the
prevEndtime (end time of the last kept interval). - Check: For each interval
curr:- If
curr.start >= prevEnd: No overlap using greedy choice. Keep it and updateprevEnd = curr.end. - Else: Overlap detected. Since
currends later (or same time) as our sortedprev, we prefer theprevone (already chosen) and removecurr. - Wait, actually since we sorted by end, if
curroverlapsprev,currMUST have a later or equal end time. So keepingprevis always optimal or neutral. Thus we blindly discardcurr.
- If
Interactive Visualization
Step 1 / 1
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
