call(back)
Algorithms & Data StructuresmediumSign in to star problems

Minimum Bus Fleet

Each trip is [from, departure, to, arrival]: a bus leaves station from at departure and reaches station to at arrival. After a trip the bus is at to, and it can take any trip that departs from that station at or after its arrival. Buses start wherever they are first needed.

Return the fewest buses that can run every trip.

minBuses([["A", 1, "B", 2], ["B", 3, "C", 4]])  ->  1     // the same bus continues from B
minBuses([["A", 1, "B", 5], ["B", 3, "C", 4]])  ->  2     // it arrives at B too late

Hints

Hint 1

Process trips in departure order. At a departure, any bus idle at that station that arrived at or before the departure time can take the trip; otherwise a new bus is needed.

Hint 2

Idle buses at the same station are interchangeable, so keep a sorted list (or a heap) of arrival times per station and pop the earliest.

Asked at