Fewest Buses Needed to Cover Every Scheduled Trip
SnowflakeSoftware Engineer · Technical ScreenLast updated
Given scheduled trips with start and end times, return the fewest buses needed so that no bus runs two trips at once, where a bus may start a trip the moment its previous one ends. It tests reasoning about maximum interval overlap and boundary handling.
A transit operator has a list of scheduled trips, each with a start time and an end time, and a bus can run only one trip at a time. Return the smallest number of buses that can cover every trip.
Function Signature
def min_buses(trips: list[list[int]]) -> int:
Rules
trips[i] = [start, end]withstart < end. The bus running tripiis busy fromstartup to, but not including,end.- A bus that finishes a trip at time
tcan start another trip at timet. - Any free bus can take any trip; travel between the end of one trip and the start of the next is not modeled.
Constraints
1 <= len(trips) <= 10^50 <= start < end <= 10^9for every trip
Examples
Example 1
Input: trips = [[1, 4], [2, 5], [7, 9], [3, 6]]
Output: 3
At time 3, the trips [1, 4], [2, 5] and [3, 6] are all running, so three buses are needed.
Example 2
Input: trips = [[1, 3], [3, 5], [5, 8]]
Output: 1
Each trip starts exactly when the previous one ends, so one bus runs all three.
Example 3
Input: trips = [[2, 10], [3, 4], [4, 6], [7, 8]]
Output: 2
The long trip needs its own bus, and the other three never overlap one another.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.