ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
import heapq
rooms = []
for start, end in sorted([(1, 4), (2, 3), (3, 5)]):
    if rooms and rooms[0] <= start:
        heapq.heapreplace(rooms, end)
    else:
        heapq.heappush(rooms, end)
print(len(rooms), sorted(rooms))
  1. A. 2 [3, 5]
  2. B. 2 [4, 5]
  3. C. 3 [3, 4, 5]
  4. D. 1 [5]

Correct answer: B. 2 [4, 5]

The interval (1, 4) starts a room. (2, 3) overlaps it, so a second room is needed. (3, 5) can reuse the room that ended at 3, which is replaced by 5, so the heap holds 4 and 5.

More Python Programming questions

Exams that ask this topic