Greedy algorithms and intervals
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Explain when a locally best choice leads to a globally best answer.
- Solve interval scheduling by sorting on end times.
- Merge overlapping intervals by sorting on start times.
Overview
#Greedy means commit now
A greedy algorithm makes the choice that looks best at each step and never revisits it. It is correct only when a local optimum provably leads to a global optimum. When it is not, you need DP or search instead.
Interval scheduling
To select the maximum number of non-overlapping intervals, sort by end time and take each interval that starts at or after the last chosen end:
function maxNonOverlapping(intervals) {
intervals.sort((a, b) => a[1] - b[1]);
let count = 0;
let lastEnd = -Infinity;
for (const [start, end] of intervals) {
if (start >= lastEnd) {
count++;
lastEnd = end;
}
}
return count;
}
Choosing the interval that ends earliest leaves the most room for the rest. That exchange argument is why sorting by end time is correct.
Merging intervals
To merge overlapping intervals, sort by start time and extend the current interval while the next one overlaps:
function merge(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const out = [];
for (const [start, end] of intervals) {
const last = out[out.length - 1];
if (last && start <= last[1]) last[1] = Math.max(last[1], end);
else out.push([start, end]);
}
return out;
}
Why greedy fails sometimes
Greedy fails when a locally attractive choice blocks a better global outcome. Coin change with arbitrary denominations is the classic example: taking the largest coin first does not always minimise the number of coins. When you cannot prove the exchange argument, reach for DP.
Practice next
- Explain why sorting by end time is correct for interval scheduling.
- Find a coin system where greedy coin change is wrong.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
For intervals [1,4], [2,3], [3,5], [6,7], what is the maximum number of non-overlapping intervals?
starter.javascript// sort by end time: [2,3], [1,4], [3,5], [6,7]Reveal the reference answer
reference.javascriptSorted by end: [2,3], [1,4], [3,5], [6,7]. Choose [2,3], then [3,5] starts at 3 which is at or after 3, choose it, then [6,7]. That is three intervals.Authored expected output: 3
Choosing the earliest-ending interval first leaves the most room.
Exercise 2Predict
Merging [1,3], [2,6], [8,10], [15,18] gives what list?
starter.javascript// sort by start, then extend while overlappingReveal the reference answer
reference.javascript[1,3] and [2,6] overlap, so they merge to [1,6]. [8,10] does not overlap, so it stays. [15,18] also stays. The result is [1,6], [8,10], [15,18].Authored expected output: [[1,6],[8,10],[15,18]]
Extending the end to the maximum keeps merged intervals correct.
Exercise 3Explain
Explain why sorting intervals by end time is correct for maximising the number of non-overlapping intervals.
Reveal the reference answer
reference.textThe interval that ends earliest leaves the largest possible remaining time for later intervals, so it can never reduce the maximum count. Any optimal solution can be exchanged to include it without losing an interval, which is the exchange argument that proves the greedy choice is safe.Authored expected output: The earliest-ending interval leaves the most room, so it is always safe to choose.
A provable exchange argument is what separates a correct greedy from a lucky one.
Common misconceptions
#- Greedy always works if it feels natural. It needs a proof such as an exchange argument.
- Sorting intervals by start always maximises non-overlapping count. End-time sorting is required for that problem.
- Greedy and DP are interchangeable. They solve different classes of problems.
Follow-up practice
#- dsa-from-zero-backtracking
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.