Greedy & interval scheduling
Exchange arguments, interval merging, meeting rooms. Knowing when greedy is provably safe vs when you need DP is a senior-signal answer.
The mental model
Greedy is the algorithm of a person who never looks back. At every step you take the option that looks best right now, commit to it, and never reconsider. Sometimes that is exactly optimal. Usually it is not. The entire skill is knowing which world you are in.
The analogy that sticks: you are booking a single conference room for a day, and twenty teams have submitted meeting requests. You want to fit the most meetings in. Your instinct might be "start with the shortest meetings" or "start with the earliest requests". Both feel reasonable and both are wrong. The correct rule is take the meeting that finishes earliest, then the next one that starts after it finishes, and repeat. Why? Because finishing early is the only thing that buys you room for everything after it. A meeting that ends at 10:00 dominates every meeting that ends at 10:30 — anything the second one could enable, the first one also enables, plus more.
That last sentence is the shape of every correct greedy proof. It is called an exchange argument: take any optimal solution, show you can swap its first choice for your greedy choice without making it worse, and repeat by induction. If you can construct that swap, greedy is provably optimal. If you cannot, greedy is a heuristic and you probably need dynamic programming.
**Why this topic exists in interviews.** Greedy problems are the cheapest way for an interviewer to tell a pattern-matcher from an engineer. A pattern-matcher sees "intervals" and types the sorting line. An engineer says: "I'll sort by end time, and here is why that's safe — any optimal schedule can be rewritten to start with the earliest-finishing interval." The second answer is a level signal. Conversely, the classic trap is a problem that *looks* greedy and is not: coin change with coins [1, 3, 4] and target 6 — greedy takes 4+1+1 (three coins), optimal is 3+3 (two). One counterexample kills the whole approach, and finding one fast is as valuable as the proof.
Intervals ride along with greedy because sorted intervals are where the exchange argument is easiest to see, and because interval problems are extremely common in real systems: calendar scheduling, rate limiting windows, log deduplication, resource booking, IP range merging, video ad-break placement.
- Deep dive
- Internal architecture
- Real-world use cases
- Best practices
- Common mistakes
- Performance
- Security
- Production troubleshooting
- Advantages & disadvantages
- Alternatives
- Interview expectations
- Interview questions
- Facts to remember
- Cheat sheet
- Quick revision