KatInterview

Fewest Vehicles to Cover Back-to-Back Bookings

Greedy & IntervalsAuto-graded · 17 test cases
MediumAuto-gradedGreedy & Intervalsintervalssweep-linesorting

Last 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, with start < 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) <= 100000
  • 0 <= start < end <= 10^9
  • All booking_id values 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.