Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

What is printed? (minimum platforms / overlapping intervals with a heap)

What is printed? (minimum platforms / overlapping intervals with a heap)
import heapq
iv = sorted([(1, 4), (2, 3), (3, 6), (5, 7), (6, 8), (7, 9)])
h = []; best = 0
for s, e in iv:
    while h and h[0] <= s: heapq.heappop(h)
    heapq.heappush(h, e); best = max(best, len(h))
print(best)
  1. A. 3
  2. B. 4
  3. C. 1
  4. D. 2

Correct answer: D. 2

Sort by start and keep a min-heap of end times of ongoing intervals; pop those ending at or before the new start (touching does not overlap here). At most two intervals are ever active together, e.g. (1,4) with (2,3) or (3,6). Counting all pairwise overlaps would be O(n²). O(n log n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic