Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: n ≤ 10⁵ trains arrive and depart at given minutes. Find the minimum number of platforms. Which approach is O(n log n) and correct?

  1. A. Sort trains by arrival and count overlaps with the next train only
  2. B. Greedy: assign each train to platform 1 if free, else open a new platform without reuse
  3. C. Sort arrivals and departures separately and sweep with two pointers, tracking the maximum number of trains present
  4. D. Binary search the answer with an O(1) check

Correct answer: C. Sort arrivals and departures separately and sweep with two pointers, tracking the maximum number of trains present

A sweep over sorted events counts trains present at every moment; the peak is the answer. Checking only adjacent trains misses three-way overlaps, and never reusing platforms over-counts. A min-heap of departure times is an equivalent O(n log n) method.

More Coding Interview Problems questions

Exams that ask this topic