Data Structures & AlgorithmsHardTCS NQT Digital · Product Company SDE

Problem: Find the minimum number of railway platforms with a sweep line over arrival and departure events (a train arriving when another departs at the same minute needs a new platform).

Problem: Find the minimum number of railway platforms with a sweep line over arrival and departure events (a train arriving when another departs at the same minute needs a new platform).
def platforms(arr, dep):
    ev = sorted([(t, 1) for t in arr] + [(t, -1) for t in dep], key=lambda e: (e[0], -e[1]))
    cur = best = 0
    for _, d in ev:
        cur += d; best = max(best, cur)
    return best
print(platforms([900, 940, 950, 1100, 1500, 1800], [910, 1200, 1120, 1130, 1900, 2000]), platforms([100, 200], [200, 300]))
What is printed?
  1. A. 3 2
  2. B. 3 1
  3. C. 2 2
  4. D. 4 2

Correct answer: A. 3 2

Sort events by time; at equal times arrivals (+1) are processed before departures, which implements 'same minute needs a new platform'. Peak overlap in the first schedule is 3 (940–1200, 950–1120, 1100–1130). At minute 200 one train arrives as another leaves → 2; processing departures first would give 1. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic