KatInterview

Smallest Vehicle Pool for Location-Bound Shuttle Runs

Greedy & IntervalsModel answer
MediumModel answerGreedy & Intervalssweep-linesortingevents

Last updated

Given timed runs between named stops, find the fewest shuttles needed when each shuttle can only continue from the stop where its previous run ended.

Smallest Vehicle Pool for Location-Bound Shuttle Runs

A transit operator publishes a list of shuttle runs. Each run is described by when it leaves, when it arrives, the stop it leaves from and the stop it arrives at. Work out the smallest number of shuttles that can cover every run.

Function contract

Implement minimum_station_buses(trips) -> int.

Each element of trips is an integer array [departure, arrival, origin, destination].

A shuttle that finishes a run at stop s at time t can take on another run only if that run starts at stop s at a time >= t. Return the minimum size of the fleet.

Rules

  • Shuttles may be placed at any stops before service starts.
  • There is no turnaround delay.
  • A shuttle can change stops only by performing a listed run. Empty repositioning is not allowed.
  • Every run must be served exactly once.
  • Stop identifiers carry no distance or travel-time meaning.

Constraints

  • 0 <= len(trips) <= 200000
  • 0 <= departure < arrival <= 1000000000
  • Stop identifiers are integers in [0, 1000000000].
  • A run may start and end at the same stop.
  • The input is not sorted. Identical records are distinct runs.
  • A shuttle that arrives at exactly the departure time of another run, at the same stop, may take that run.
  • An empty schedule returns 0.
  • Aim for O(n log n) time or better.

Examples

trips = [[0, 4, 1, 2], [4, 7, 2, 1], [4, 6, 1, 2]]
Output: 2

The shuttle finishing the first run is at stop 2 at time 4, so it can take the second run. The third run leaves stop 1 and needs a second shuttle.

trips = [[0, 2, 1, 2], [3, 5, 1, 2]]
Output: 2

The runs do not overlap in time, but the first shuttle ends at stop 2 and cannot get back to stop 1 without an empty move.

What to provide

Explain your approach, justify why it gives the true minimum, state the complexity, and give code.

Hints

Hint 1

Think about why the classic 'maximum number of overlapping intervals' answer fails here. What does the second example show?

Hint 2

Within one stop, shuttles are interchangeable, and the stream of shuttles arriving at that stop is fixed by the schedule regardless of which shuttle serves which run. So each stop can be analyzed independently.

Hint 3

For a single stop, count departures minus arrivals as time advances. The largest positive value of that running difference is how many shuttles must begin there. Decide how to order an arrival and a departure with the same timestamp.