ProgrammingHardTCS NQT · Accenture

Intervals (start, end): (1,10), (2,3), (4,5), (6,7), (8,9). The greedy below selects the largest set of pairwise disjoint intervals, sorted by end time. What is printed?

Intervals (start, end): (1,10), (2,3), (4,5), (6,7), (8,9). The greedy below selects the largest set of pairwise disjoint intervals, sorted by end time. What is printed?
sort intervals by end ascending
last = 0; count = 0
for each (s, e) in sorted order
    if s > last then count = count + 1; last = e
end for
Print count
  1. A. 4
  2. B. 1
  3. C. 5
  4. D. 2

Correct answer: A. 4

Sorted by end time the order is (2,3), (4,5), (6,7), (8,9), (1,10); the greedy takes the four short intervals and rejects (1,10), printing 4. Sorting by start picks (1,10) first and blocks everything (1), counting every interval ignores overlap (5), and requiring a gap of more than one unit between picks keeps only (2,3) and (6,7) (2).

More Pseudocode and Code Tracing questions

Exams that ask this topic