Data Structures & AlgorithmsHardProduct Company SDE · ICPC regional

Intervals (start, end) are compatible when one ends at or before the other starts. Run the earliest-finish greedy on the list below and report how many intervals it keeps.

Intervals (start, end) are compatible when one ends at or before the other starts. Run the earliest-finish greedy on the list below and report how many intervals it keeps.
iv=[(1,4),(3,5),(0,6),(5,7),(3,9),(5,9),(6,10),(8,11),(8,12),(2,14),(12,16)]
c=0; e=-1
for s,t in sorted(iv,key=lambda x:x[1]):
    if s>=e: c+=1; e=t
print(c)
What number does it print?
  1. A. 3
  2. B. 4
  3. C. 1
  4. D. 11

Correct answer: B. 4

Earliest-finish greedy is optimal for interval scheduling. Sorting by start can pick a long interval that blocks two short ones, sorting by start descending is a nonsense order, and forgetting to update the boundary after taking an interval lets every interval through.

More Coding Interview Problems questions

Exams that ask this topic