Peak number of bikes needed to cover all pre-booked rental intervals
FaireSoftware Engineer · OnsiteLast updated
Given every booking for a bike rental service as a start and end time, compute the peak number of bikes in use at the same moment, which is the smallest fleet that serves all bookings. Tests interval-overlap reasoning, half-open boundary handling and an efficient method for up to 100,000 unsorted bookings.
A bike rental service receives every booking ahead of time. Each booking reserves one bike from a start time until an end time. Write a function that returns the peak number of bikes needed at any point in time: the number of bookings in use at the busiest moment, which is also the smallest fleet that can serve every booking.
Function Signature
def peak_bike_demand(bookings: list[list[int]]) -> int:
Rules
bookings[i] = [start, end]reserves one bike for the half-open interval[start, end): the bike is in use at every timetwithstart <= t < end.- A bike returned at time
tcan be rented out again at timet, so a booking that ends attand a booking that starts attnever need two bikes at once. - Bikes are interchangeable. Identical bookings are separate bookings, and each needs its own bike.
- Return the maximum, over all times
t, of the number of bookings in use att. Return0when there are no bookings.
Constraints
0 <= len(bookings) <= 10^50 <= start < end <= 10^9for every booking- Times are integers (for example, minutes from the start of the booking period), so every value fits in a 32-bit signed integer.
bookingsis in no particular order.
Examples
Example 1
Input: bookings = [[1, 4], [2, 5], [7, 9], [3, 6]]
Output: 3
At time 3, the bookings [1, 4), [2, 5) and [3, 6) are all in use. No moment has more.
Example 2
Input: bookings = [[1, 3], [3, 5], [5, 7]]
Output: 1
Each booking starts exactly when the previous one ends, so one bike can serve all three in turn.
Example 3
Input: bookings = [[5, 10], [5, 10], [9, 12], [10, 11]]
Output: 3
At time 9, both copies of [5, 10) and the booking [9, 12) are in use. At time 10, the two copies have ended, leaving [9, 12) and [10, 11).
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.