1. Sort by end
Sorting by end lets you greedily keep the interval that frees up soonest.
intervals.sort((a, b) => a[1] - b[1])Typorithm · medium
Step 1 of 8 · intro card
Intervals
Sort by end; greedily keep each interval that starts after the last kept end, counting the rest as removals.
To remove the fewest intervals, keep as many compatible ones as possible.
Sorting by end and always keeping the interval that finishes earliest leaves the most room for the rest.
Any interval starting before the last kept end conflicts and is counted as a removal.
Sort by END, not start.
Keep the earliest-ending compatible interval.
Count conflicts as removals.
function eraseOverlapIntervals(intervals) {
intervals.sort((a, b) => a[1] - b[1]);
let prevEnd = -Infinity;
let removed = 0;
for (const [start, end] of intervals) {
if (start >= prevEnd) {
prevEnd = end;
} else {
removed += 1;
}
}
return removed;
}Connect each part of the code to the concept before you type.
Sorting by end lets you greedily keep the interval that frees up soonest.
intervals.sort((a, b) => a[1] - b[1])If this interval starts after the last kept end, keep it.
if (start >= prevEnd) {Update the boundary to the kept interval's end.
prevEnd = endAn overlapping interval is removed instead.
removed += 1Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.