ProgrammingHardCapgemini · TCS NQT

Closed intervals (start, end): (1,4), (2,6), (8,10), (9,12), (11,13), (3,5). The greedy below places points so that every interval contains at least one point. What is printed?

Closed intervals (start, end): (1,4), (2,6), (8,10), (9,12), (11,13), (3,5). The greedy below places points so that every interval contains at least one point. What is printed?
sort intervals by end ascending
last = -infinity; points = 0
for each (s, e) in sorted order
    if s > last then last = e; points = points + 1
end for
Print points
  1. A. 3
  2. B. 6
  3. C. 5
  4. D. 2

Correct answer: A. 3

Placing a point at the earliest end covers every interval that starts at or before it, which gives 3 points. Counting intervals gives 6, setting last to the start instead of the end over-counts, and demanding a gap of one unit in the test changes the answer.

More Pseudocode and Code Tracing questions

Exams that ask this topic