ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import heapq
iv = sorted([(0, 30), (5, 10), (15, 20)])
h = []
for s, e in iv:
    if h and h[0] <= s:
        heapq.heapreplace(h, e)
    else:
        heapq.heappush(h, e)
print(len(h))
  1. A. 3
  2. B. 0
  3. C. 2
  4. D. 1

Correct answer: C. 2

This is the minimum-rooms check. The heap holds the end times of rooms in use. Interval (0, 30) needs a room, (5, 10) cannot reuse it so it needs a second, and (15, 20) can reuse the room that ends at 10.

More Python Programming questions

Exams that ask this topic