Fewest Vehicles to Cover Back-to-Back Bookings
Greedy & IntervalsAuto-graded · 17 test casesLast updated
Find the peak number of simultaneously active half-open intervals using a sweep line or heap, with correct handling of ties where one booking ends as another begins.
Fleet Sizing for Bookings
A vehicle-sharing service has received a batch of bookings. Each booking is a list [booking_id, start, end], where booking_id is a string and start and end are integer timestamps.
A booking occupies a vehicle for the half-open span [start, end). This means a vehicle that comes back at time t can be handed to another customer who starts at exactly time t. Two bookings conflict only if their spans share some moment strictly inside both, so a booking ending at t and another starting at t do not conflict.
Any single vehicle can serve several bookings one after another, provided none of them conflict. Return the smallest number of vehicles that can serve every booking.
Input
bookings: a list of[booking_id, start, end]entries, withstart < end.
Output
- An integer: the minimum number of vehicles needed. If there are no bookings, return
0.
Notes
- Several bookings may share the same start, the same end, or both. Identical spans each need their own vehicle.
- When a return and a start happen at the same timestamp, the return takes effect first.
Constraints
0 <= len(bookings) <= 1000000 <= start < end <= 10^9- All
booking_idvalues are distinct strings.
Examples
Example 1
Input: min_vehicles_required([['req_1', 1, 5], ['req_2', 5, 10], ['req_3', 2, 6]])
Output: 2
Example 2
Input: min_vehicles_required([['req_A', 10, 20], ['req_B', 12, 18], ['req_C', 15, 25], ['req_D', 20, 30]])
Output: 3
Hints
Hint 1
Think about a single moment in time: how many bookings are using a vehicle at that moment? The answer can never be smaller than the largest such count.
Hint 2
Convert each booking into two events, a start (+1) and an end (-1), sort them by time, and keep a running count of active bookings.
Hint 3
At equal timestamps, process ends before starts. Sorting event tuples as (time, delta) with delta in {-1, +1} does this automatically.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The answer equals the maximum number of bookings that are active at the same moment.
- Lower bound: if
kbookings are active at some instant, each needs a different vehicle, so at leastkvehicles are required. - Upper bound: process bookings in order of start time and give each one any vehicle that has already been returned, opening a new vehicle only if all existing ones are busy. A new vehicle is opened only when every current vehicle is in use at that start time, so the fleet size never exceeds the peak overlap.
To compute the peak overlap, use a sweep line:
- For every booking, create an event
(start, +1)and an event(end, -1). - Sort events by time. For equal times,
-1sorts before+1, so returns are applied before new starts. This matches the half-open spans. - Scan the events, maintaining a running count of active bookings, and record the largest value.
Why it is correct
After applying all events up to and including time t (ends before starts), the running count equals the number of bookings with start <= t < end, which is exactly the set of bookings active at t. The count only changes at event times, so the maximum seen during the scan is the true peak. If starts were processed first at a tied timestamp, a finished booking would be counted together with a new one and the peak would be overstated.
Complexity
- Time:
O(n log n), dominated by sorting2nevents. - Space:
O(n)for the events.
Timestamps are only compared, never used as indices, so their magnitude (up to 10^9) does not matter. An empty input produces no events and returns 0.
Reference solution
from typing import List
def min_vehicles_required(bookings: List[List]) -> int:
events = []
for booking_id, start, end in bookings:
events.append((start, 1))
events.append((end, -1))
# Sort by time; at equal times -1 (end) comes before +1 (start).
events.sort()
active = 0
best = 0
for _, delta in events:
active += delta
if active > best:
best = active
return best