Skip to interview prep
Apexed

To select the maximum number of non-overlapping intervals, should you pick by earliest start, shortest length, or earliest finish? Give counterexamples.

MediumGreedy algorithms

Technical

Content review

Report an error

Not yet reviewed

Getting your answer ready…

Show model answer

Sort by finish time and take each interval whose start is at or after the finish of the last one taken. This is O(n log n) for the sort plus O(n) for the scan, with O(1) extra space beyond the sort. It is optimal by a 'greedy stays ahead' argument: after k picks, the greedy's k-th finish time is never later than the k-th finish time of any other valid schedule, so it can always fit at least as many intervals.

Earliest start fails on [0,10], [1,2], [3,4]: it takes [0,10] and blocks the two short intervals (1 versus 2). Shortest first fails on [0,5], [4,7], [6,10]: the shortest, [4,7], overlaps both others (1 versus 2). 'Fewest conflicts first' also has known counterexamples, so only earliest finish is safe.

What interviewers listen for

  • Earliest finish time is optimal
  • Earliest start and shortest both have small counterexamples

Example program

To select the maximum number of non-overlapping intervals, should you pick by earliest start, shortest length, or earliest finish? Give counterexamples. — Data