Smallest Vehicle Pool for Location-Bound Shuttle Runs
Greedy & IntervalsModel answerLast 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) <= 2000000 <= 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why the usual answer fails
Without stops, the minimum fleet equals the maximum number of simultaneously running trips. Here a free shuttle is useless if it is at the wrong stop. In the second example nothing overlaps, yet two shuttles are needed. The fix is to stop thinking about the whole fleet and look at each stop separately.
Two observations
- The arrivals at each stop are fixed. Every run is served exactly once, so the set of (stop, time) arrival events is determined by the schedule alone. Which shuttle performs a run does not change it.
- Shuttles at one stop are interchangeable. A departure from stop
sonly needs some idle shuttle ats.
So for each stop, the only question is how many shuttles must be there at the start so that no departure finds the stop empty.
Per-stop sweep
Sort the events at stop s by time:
- an arrival adds one idle shuttle,
- a departure consumes one idle shuttle.
Let balance(t) be (departures up to t) minus (arrivals up to t). The number of shuttles that must start at s is
need(s) = max(0, max over t of balance(t))
At equal timestamps, process arrivals before departures, because a shuttle arriving exactly at the departure time can be used. The answer is the sum of need(s) over all stops.
Correctness
Lower bound. Fix a stop s and a time t. Every departure from s at or before t needs its own shuttle present at s. A shuttle is at s either because it started there or because it arrived there on a run. So the number of starting shuttles at s is at least departures(<=t) - arrivals(<=t). Taking the maximum over t gives need(s). Each shuttle starts at exactly one stop, so any valid fleet has at least the sum of need(s) shuttles.
Achievability. Place need(s) shuttles at each stop s. Process each stop's timeline and give any idle shuttle to each departure. By the definition of need(s), the idle count never goes negative, so every departure is served. The shuttle that serves a run then appears at the destination, which is exactly the arrival event already counted in that destination's timeline. The per-stop simulations are therefore consistent with each other, and the lower bound is met.
Ties. Since departure < arrival for every run, a run's own arrival can never feed its own departure, even when origin equals destination. Placing arrivals first at equal times only allows other runs to reuse a shuttle, which is permitted.
Complexity
- Time:
O(n log n)for sorting2nevents, plusO(n)for the sweep. - Space:
O(n)for the events.
No heaps per stop and no bipartite matching are needed.
Code
from typing import List
def minimum_station_buses(trips: List[List[int]]) -> int:
# (stop, time, kind): kind 0 = arrival (shuttle becomes idle),
# kind 1 = departure (shuttle required). Arrivals sort first on ties.
events = []
for dep, arr, origin, dest in trips:
events.append((origin, dep, 1))
events.append((dest, arr, 0))
events.sort()
total = 0
current = None
balance = 0
worst = 0
for stop, _t, kind in events:
if stop != current:
total += worst
current = stop
balance = 0
worst = 0
if kind == 1:
balance += 1
if balance > worst:
worst = balance
else:
balance -= 1
total += worst
return total
Walkthrough of example 1
Runs: [0,4,1,2], [4,7,2,1], [4,6,1,2].
| Stop | Events in order | Running balance | need |
|---|---|---|---|
| 1 | dep@0, dep@4, arr@7 | 1, 2, 1 | 2 |
| 2 | arr@4, dep@4, arr@6 | -1, 0, -1 | 0 |
Total: 2. In example 2, stop 1 has two departures and no arrivals, so it needs 2, and stop 2 only receives shuttles. Total: 2.
Edge cases
- Empty input gives no events and the answer
0. - Same origin and destination: a departure and a strictly later arrival at the same stop, handled naturally.
- Identical records generate separate events, so concurrent duplicates need separate shuttles.
- Exact-time handoff works because arrivals sort before departures.
- Large stop IDs are fine because we sort on them directly rather than indexing an array.
- Unsorted input is handled by the global sort.
Common mistakes
- Using a single global min-heap of end times. It reuses shuttles that are at the wrong stop and fails the second example.
- Processing departures before arrivals at equal times, which overcounts.
- Building a path-cover bipartite matching over all compatible run pairs. It is correct in principle but has
O(n^2)edges, far too slow forn = 200000. - Allowing empty repositioning, which collapses the problem back to maximum overlap.
- Forgetting to add the last stop's
worstafter the loop ends.
Follow-ups worth discussing
- If repositioning were allowed at a known cost or travel time, the problem becomes a min-cost flow or path-cover problem, and the per-stop decomposition no longer holds.
- If a turnaround time were required, an arrival at time
twould become available att + gap, so you would shift the arrival timestamp before sorting. - If you also needed to output the actual assignment, keep a per-stop stack of idle shuttles and pop one for each departure.