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)- A. 3
- B. 4
- C. 1
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- A complete binary tree is stored in an array with the root at index 1. A node at index 37 – what are its parent, left child and right…
- What is printed? (Catalan-style recursion with memo: number of ways to fully parenthesise a product of n matrices) python from functools…
- Union–find with union by rank and full path compression. What is printed? python p = list(range(8)); rank = [0] 8 def find(x): if p[x] !=…
- 0-1 BFS on a grid: stepping into '#' costs 1 (a wall to break), stepping onto '.' or 'T' costs 0. What is the minimum number of walls to…
- How many topological orders does this DAG on 6 vertices have? (counted by DP over bitmasks of already-placed vertices) python from…
- Fenwick (binary indexed) tree, 1-based, built by point additions; then a[3] += 10. What is printed (the internal array, a range sum and a…