1. Sort by finish
Sorting by finish time makes the earliest-ending interval the safe greedy pick.
intervals.sort((a, b) => a[1] - b[1])Typorithm · medium
Step 1 of 8 · intro card
Greedy
Sort by finish time, then keep every interval that starts after the last kept one ends.
The goal is to keep as many non-overlapping intervals as possible.
The greedy choice is to always keep the interval that finishes earliest, because it leaves the most room for the rest.
Sorting by finish time once, then a single linear scan, gives the optimal answer.
Sort by finish time, not start time.
Greedy pick: earliest finish that fits.
Keep when start >= last finish.
function maxNonOverlapping(intervals) {
intervals.sort((a, b) => a[1] - b[1]);
let count = 0;
let end = -Infinity;
for (const [start, finish] of intervals) {
if (start >= end) {
count += 1;
end = finish;
}
}
return count;
}Connect each part of the code to the concept before you type.
Sorting by finish time makes the earliest-ending interval the safe greedy pick.
intervals.sort((a, b) => a[1] - b[1])Track the finish time of the last interval we kept.
let end = -InfinityWalk the intervals from earliest finish to latest.
for (const [start, finish] of intervals)Keep an interval only when it starts at or after the last kept finish.
if (start >= end)After keeping an interval, its finish becomes the new boundary.
end = finishRead 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.
Algorithm lab · interactive
InputIntervals [[1,3],[2,5],[4,7],[6,9],[8,10]]
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state