Smallest Vehicle Fleet for Booking Intervals

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

You run a vehicle-sharing dispatch service and receive a batch of confirmed bookings requests. Each booking is represented as a 3-element sequence [request_id, pickup_time, return_time] (either a list or a 3-element tuple / NamedTuple), containing: - request_id: a unique string identifier for the reservation, - pickup_time: the integer timestamp when the customer takes the vehicle, - return_time: the integer timestamp when the vehicle comes back (pickup_time < return_time).

Every reservation occupies one vehicle across the half-open time window [pickup_time, return_time). A vehicle brought back at timestamp t can immediately go back out for another reservation whose pickup_time is t.

Implement:

def min_cars_needed(requests: List[List]) -> int:

Return the smallest fleet size needed so every reservation in requests is served without double-booking any vehicle.

Examples

Example 1

Input:
requests = [
  ["bk_1", 2, 7],
  ["bk_2", 7, 12],
  ["bk_3", 3, 8],
  ["bk_4", 4, 6]
]
Output: 3

Across [4, 6), bk_1, bk_3, and bk_4 are simultaneously active, requiring 3 distinct vehicles. When bk_1 ends at timestamp 7, bk_2 immediately reuses that returned vehicle, so no fourth vehicle is needed.

Example 2

Input:
requests = [
  ["res_x", 0, 4],
  ["res_y", 4, 9],
  ["res_z", 1, 4],
  ["res_w", 4, 8]
]
Output: 2

res_x and res_z overlap on [1, 4) using 2 vehicles. Because intervals are half-open, both vehicles return at t = 4 before res_y and res_w depart at t = 4, keeping peak usage at 2.

Constraints

  • 0 <= len(requests) <= 100,000
  • 0 <= pickup_time < return_time <= 10^9
  • All request_id strings are distinct.
  • An empty requests list requires 0 vehicles.

Step-by-step walkthrough

  1. Understand the input shape and half-open intervals

    Each booking arrives as a 3-element sequence [request_id, pickup_time, return_time] (reading request[1] and request[2] works identically whether the caller passes lists, plain tuples, or RentalRequest named tuples). Every booking occupies one car across the half-open interval [pickup_time, return_time), meaning the car is busy starting at pickup_time and becomes free again at the exact instant return_time.

    Let's visualize Example 1 ([2, 7), [7, 12), [3, 8), [4, 6)):

    Time:    2   3   4   5   6   7   8   9   10  11  12
    bk_1:   [===================)
    bk_2:                       [===================)   <- reuses bk_1's car at t=7!
    bk_3:       [===================)                   <- overlaps bk_1 on [3, 7), needs Car 2
    bk_4:           [=======)                           <- overlaps both on [4, 6), needs Car 3
    

    Notice request_id never changes how many cars we need — only the start and end timestamps matter.

  2. Why minimum fleet size equals peak simultaneous overlap

    Let peak be the maximum number of requests that are active at the exact same instant. Why is peak always the exact minimum number of cars required?

    • At least peak cars are necessary: At the moment when peak bookings overlap, each of those peak customers is driving a separate physical car, so fewer than peak cars cannot possibly serve them all.
    • peak cars are always sufficient: Imagine handing out cars in pickup_time order and always reusing any car that has already been returned. The only time you are forced to buy a k-th car is when all k - 1 existing cars are still out on the road at this new booking's pickup_time. At that instant, those k - 1 earlier bookings plus the new booking make k bookings active simultaneously — so k can never exceed peak!

    That turns "assign cars to bookings" into a simpler counting question: what is the maximum number of intervals covering any single point in time?

  3. Why naive overlap counting is too slow

    How might we try to find the peak overlap at first?

    1. Count active intervals at every integer timestamp 0 .. 10^9: Timestamps reach 10^9, so creating a timeline array of length 10^9 would consume gigabytes of RAM and time out immediately.
    2. Count active intervals at each booking's pickup_time: Because overlap only increases when a new booking starts, the peak must occur at some pickup_time. Checking all N intervals against all N pickup times avoids the 10^9 array, but takes O(N^2) work — around 10^10 checks when N = 100,000, which takes several seconds too long in Python.

    Instead of recounting active bookings from scratch at every pickup, we can maintain a single running counter as time moves forward.

  4. Turn intervals into sorted events with tie-breaking

    Every booking [pickup_time, return_time) changes the number of busy cars only twice: - At pickup_time, busy cars change by +1. - At return_time, busy cars change by -1.

    If we put all 2N events (timestamp, delta) into one list and sort them chronologically, sweeping through the list updates active_cars += delta in O(1) per event!

    Watch out for the one critical boundary case: what happens when one car is returned at t = 7 and another is picked up at t = 7?

    Wrong order (PICKUP before RETURN at t=7):
      (2, +1) -> active=1
      (7, +1) -> active=2   <-- false spike! Counted both bk_1 and bk_2 at t=7
      (7, -1) -> active=1
    
    Right order (RETURN before PICKUP at t=7):
      (2, +1) -> active=1
      (7, -1) -> active=0   <-- bk_1 frees its car first
      (7, +1) -> active=1   <-- bk_2 immediately reuses that car
    

    Because Python compares (timestamp, delta) tuples element by element and -1 < +1, storing RETURN = -1 and PICKUP = 1 automatically sorts every return at timestamp t ahead of every pickup at timestamp t!

    # At equal timestamps, RETURN (-1) is smaller than PICKUP (+1), so Python's tuple sort
    # processes all car returns at time t BEFORE any car pickups at time t.
    RETURN = -1
    PICKUP = 1
    
    
    def min_cars_needed(requests: List[List]) -> int:
        # Phase 1: Convert each half-open booking [pickup_time, return_time) into two events.
        # events: list of (timestamp, delta) tuples, e.g. [(2, +1), (7, -1), ...]
        events: List[Tuple[int, int]] = []
        for request in requests:
            # Read indices 1 and 2 so both [id, pickup, ret] lists and NamedTuples work identically.
            pickup_time = request[1]
            return_time = request[2]
            events.append((pickup_time, PICKUP))
            events.append((return_time, RETURN))
    
        # Sorting orders by timestamp first, and puts RETURN (-1) before PICKUP (+1) on ties.
        events.sort()
    
        # Phase 2: Sweep chronologically and record the highest number of cars out at once.
        active_cars = 0
        peak_cars = 0
        for timestamp, delta in events:
            active_cars += delta
            if active_cars > peak_cars:
                peak_cars = active_cars
    
        return peak_cars
    
  5. Walk through Example 2 step by step

    Let's trace Example 2: res_x: [0, 4), res_y: [4, 9), res_z: [1, 4), res_w: [4, 8).

    Sorted event          Meaning           active_cars   peak_cars
    -------------------   ---------------   -----------   ---------
    (0, +1)               res_x picked up        1            1
    (1, +1)               res_z picked up        2            2   <- 2 cars out on [1, 4)
    (4, -1)               res_x returned         1            2   <- returns run first at t=4
    (4, -1)               res_z returned         0            2
    (4, +1)               res_y picked up        1            2   <- reuses freed car
    (4, +1)               res_w picked up        2            2   <- reuses second freed car
    (8, -1)               res_w returned         1            2
    (9, -1)               res_y returned         0            2
    

    The running count peaks at 2, so min_cars_needed returns 2.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # At equal timestamps, RETURN (-1) is smaller than PICKUP (+1), so Python's tuple sort
    # processes all car returns at time t BEFORE any car pickups at time t.
    RETURN = -1
    PICKUP = 1
    
    
    def min_cars_needed(requests: List[List]) -> int:
        # Phase 1: Convert each half-open booking [pickup_time, return_time) into two events.
        # events: list of (timestamp, delta) tuples, e.g. [(2, +1), (7, -1), ...]
        events: List[Tuple[int, int]] = []
        for request in requests:
            # Read indices 1 and 2 so both [id, pickup, ret] lists and NamedTuples work identically.
            pickup_time = request[1]
            return_time = request[2]
            events.append((pickup_time, PICKUP))
            events.append((return_time, RETURN))
    
        # Sorting orders by timestamp first, and puts RETURN (-1) before PICKUP (+1) on ties.
        events.sort()
    
        # Phase 2: Sweep chronologically and record the highest number of cars out at once.
        active_cars = 0
        peak_cars = 0
        for timestamp, delta in events:
            active_cars += delta
            if active_cars > peak_cars:
                peak_cars = active_cars
    
        return peak_cars
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine standing at the exit gate of the rental lot with a handheld clicker counter. Every time a customer drives a car out of the lot, you click +1; every time a customer brings a car back, you click -1. The highest number your clicker ever shows during the day is the exact minimum fleet size the company needs! Turning intervals into discrete start/end changes and walking through them in chronological order is called a sweep-line algorithm (an algorithm that moves a virtual time marker across sorted events and updates a running state at each stop).

Why do more obvious ideas fall short? Creating an array indexed by every timestamp up to 10^9 runs out of memory immediately, while checking how many bookings overlap each of the 100,000 pickup times with nested loops takes O(N^2) (10^10 comparisons). Even sorting bookings by pickup time and comparing each booking only with the immediately previous one fails, because an earlier long-term rental may still be on the road after several shorter rentals have come and gone.

Because each booking covers a half-open interval [pickup_time, return_time) (meaning pickup_time is included, while at return_time the car is already free again), returns at timestamp t must happen before pickups at t. Encoding returns as -1 and pickups as +1 inside (timestamp, delta) tuples makes Python's sort do this automatically, as shown on Example 2 ([0, 4), [4, 9), [1, 4), [4, 8)):

Sorted events:  (0, +1) -> (1, +1) -> (4, -1) -> (4, -1) -> (4, +1) -> (4, +1) -> (8, -1) -> (9, -1)
active_cars:       1          2          1          0          1          2          1          0
                                         ^          ^
                         at t=4, both -1 events run before +1 so active_cars drops to 0
                         before climbing back to 2 (never falsely hitting 4!)
Peak active_cars = 2

Complexity

Let N be the number of rental requests (len(requests)).

  • Time: O(N log N). Building the 2N (timestamp, delta) event tuples takes O(N) time, sorting 2N tuples takes O(N log N) time, and sweeping once across the sorted list takes O(N) time.
  • Space: O(N). The events list stores 2N two-integer tuples, and Python's Timsort sorts that list in place using at most O(N) temporary merge space.

Edge cases

  • Empty input (requests = []): events is empty, the loop never runs, and peak_cars returns 0.
  • Single request: One +1 followed by one -1 gives peak_cars = 1.
  • Back-to-back chain ([0, 3), [3, 7), [7, 10)): At t = 3 and t = 7, (t, -1) runs before (t, +1), so active_cars alternates 1 -> 0 -> 1 and returns 1.
  • Multiple returns and pickups at the exact same timestamp: All -1 events at t sort before all +1 events at t, freeing every returning vehicle before handing cars out to new pickups.
  • Identical intervals (k copies of [2, 9)): All k (2, +1) tuples come before all k (9, -1) tuples, reaching peak_cars = k.
  • Extreme timestamps (0 up to 10^9) and tuple/list inputs: Sorting only compares timestamp values, so large integers add zero memory overhead, and indexing request[1] / request[2] works for both lists and RentalRequest named tuples.

Common mistakes

  • Sorting pickups before returns on timestamp ties: If you encode events as (timestamp, "pickup") and (timestamp, "return"), "pickup" < "return" alphabetically, so pickups run first at t = 4 and Example 2 wrongly returns 4 instead of 2!
  • Merging overlapping intervals and counting group sizes: [0, 2), [1, 3), and [2, 4) merge into a single contiguous block [0, 4) of 3 bookings, yet [0, 2) and [2, 4) share the same car so only 2 cars are needed.
  • Comparing only adjacent sorted bookings: Checking requests[i].pickup < requests[i - 1].return misses earlier long bookings like [0, 100) when followed by [10, 12) and [15, 18).
  • Allocating a difference array up to max(return_time): diff = [0] * (10**9 + 1) uses gigabytes of memory even when there are only 3 bookings.

Alternative approaches

  • Sort by pickup + min-heap of return times: Sort bookings by pickup_time and maintain a min-heap (heapq — a priority queue stored in a list whose 0-th element is always the smallest return_time in O(1) time, with O(log N) push/pop). For each booking, if heap is non-empty and heap[0] <= pickup_time, pop that returned car; then push return_time. Because we pop at most one car per new pickup and push one back, the heap size never shrinks and ends equal to peak_cars in O(N log N) time and O(N) space.

Follow-up questions

  • How can you extend the algorithm to produce a concrete schedule mapping each vehicle (1 .. K) to the request_ids it serves? Sort requests by pickup_time and store (return_time, car_id) pairs in a min-heap of currently busy cars. For each booking (pickup_time, return_time, request_id), if busy_heap is non-empty and busy_heap[0][0] <= pickup_time, pop (old_return, car_id) to reuse that car; otherwise allocate a brand-new car_id = len(assignments) + 1. Append request_id to assignments[car_id] and push (return_time, car_id) back onto busy_heap — this runs in O(N log N) time and opens at most peak car IDs.
  • What changes if every returned vehicle needs C units of maintenance downtime before its next departure? A car returned at return_time cannot serve another customer until return_time + C, so simply replace return_time with return_time + C when creating return events (treating each booking as [pickup_time, return_time + C)). Even for a car's final trip of the day, this never overcounts: if k extended intervals [p_i, r_i + C) all contain some instant t, then for any two of them with p_i <= p_j we have p_j <= t < r_i + C, proving neither booking could finish maintenance in time to serve the other!
  • Suppose you only own M vehicles and may decline bookings. How would you choose a feasible subset of bookings with the largest combined duration? Picking the longest requests greedily fails (for M = 1, taking [0, 10) yields 10, whereas taking [0, 6) and [6, 12) yields 12). When M = 1, this is weighted interval scheduling (sort by return_time, binary-search the latest non-overlapping booking prev[i] with return <= pickup_i, and compute dp[i] = max(dp[i - 1], duration_i + dp[prev[i]]) in O(N log N) time). For general M > 1, model the timeline as a minimum-cost flow network (a directed graph where each edge has a capacity limit and a per-unit cost, and a solver pushes M units of flow at the smallest total cost): link consecutive unique timestamps with capacity-M, cost-0 idle edges, add a capacity-1, cost-(-duration) edge from pickup_time to return_time for each request, and push M cars from start to end so at most M chosen requests overlap at any instant.

Follow-up questions

Similar questions

More Google interview questions

All 1125 Google questions →