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,0000 <= pickup_time < return_time <= 10^9- All
request_idstrings are distinct. - An empty
requestslist requires0vehicles.
Step-by-step walkthrough
Understand the input shape and half-open intervals
Each booking arrives as a 3-element sequence
[request_id, pickup_time, return_time](readingrequest[1]andrequest[2]works identically whether the caller passes lists, plain tuples, orRentalRequestnamed tuples). Every booking occupies one car across the half-open interval[pickup_time, return_time), meaning the car is busy starting atpickup_timeand becomes free again at the exact instantreturn_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 3Notice
request_idnever changes how many cars we need — only the start and end timestamps matter.Why minimum fleet size equals peak simultaneous overlap
Let
peakbe the maximum number of requests that are active at the exact same instant. Why ispeakalways the exact minimum number of cars required?- At least
peakcars are necessary: At the moment whenpeakbookings overlap, each of thosepeakcustomers is driving a separate physical car, so fewer thanpeakcars cannot possibly serve them all. peakcars are always sufficient: Imagine handing out cars inpickup_timeorder and always reusing any car that has already been returned. The only time you are forced to buy ak-th car is when allk - 1existing cars are still out on the road at this new booking'spickup_time. At that instant, thosek - 1earlier bookings plus the new booking makekbookings active simultaneously — sokcan never exceedpeak!
That turns "assign cars to bookings" into a simpler counting question: what is the maximum number of intervals covering any single point in time?
- At least
Why naive overlap counting is too slow
How might we try to find the peak overlap at first?
- Count active intervals at every integer timestamp
0 .. 10^9: Timestamps reach10^9, so creating a timeline array of length10^9would consume gigabytes of RAM and time out immediately. - Count active intervals at each booking's
pickup_time: Because overlap only increases when a new booking starts, the peak must occur at somepickup_time. Checking allNintervals against allNpickup times avoids the10^9array, but takesO(N^2)work — around10^10checks whenN = 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.
- Count active intervals at every integer timestamp
Turn intervals into sorted events with tie-breaking
Every booking
[pickup_time, return_time)changes the number of busy cars only twice: - Atpickup_time, busy cars change by+1. - Atreturn_time, busy cars change by-1.If we put all
2Nevents(timestamp, delta)into one list and sort them chronologically, sweeping through the list updatesactive_cars += deltainO(1)per event!Watch out for the one critical boundary case: what happens when one car is returned at
t = 7and another is picked up att = 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 carBecause Python compares
(timestamp, delta)tuples element by element and-1 < +1, storingRETURN = -1andPICKUP = 1automatically sorts every return at timestamptahead of every pickup at timestampt!# 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_carsWalk 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 2The running count peaks at
2, somin_cars_neededreturns2.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 the2N(timestamp, delta)event tuples takesO(N)time, sorting2Ntuples takesO(N log N)time, and sweeping once across the sorted list takesO(N)time. - Space:
O(N). Theeventslist stores2Ntwo-integer tuples, and Python's Timsort sorts that list in place using at mostO(N)temporary merge space.
Edge cases
- Empty input (
requests = []):eventsis empty, the loop never runs, andpeak_carsreturns0. - Single request: One
+1followed by one-1givespeak_cars = 1. - Back-to-back chain (
[0, 3),[3, 7),[7, 10)): Att = 3andt = 7,(t, -1)runs before(t, +1), soactive_carsalternates1 -> 0 -> 1and returns1. - Multiple returns and pickups at the exact same timestamp: All
-1events attsort before all+1events att, freeing every returning vehicle before handing cars out to new pickups. - Identical intervals (
kcopies of[2, 9)): Allk(2, +1)tuples come before allk(9, -1)tuples, reachingpeak_cars = k. - Extreme timestamps (
0up to10^9) and tuple/list inputs: Sorting only compares timestamp values, so large integers add zero memory overhead, and indexingrequest[1]/request[2]works for bothlists andRentalRequestnamed 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 att = 4and Example 2 wrongly returns4instead of2! - Merging overlapping intervals and counting group sizes:
[0, 2),[1, 3), and[2, 4)merge into a single contiguous block[0, 4)of3bookings, yet[0, 2)and[2, 4)share the same car so only2cars are needed. - Comparing only adjacent sorted bookings: Checking
requests[i].pickup < requests[i - 1].returnmisses 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 only3bookings.
Alternative approaches
- Sort by pickup + min-heap of return times: Sort bookings by
pickup_timeand maintain a min-heap (heapq— a priority queue stored in a list whose0-th element is always the smallestreturn_timeinO(1)time, withO(log N)push/pop). For each booking, ifheapis non-empty andheap[0] <= pickup_time, pop that returned car; then pushreturn_time. Because we pop at most one car per new pickup and push one back, the heap size never shrinks and ends equal topeak_carsinO(N log N)time andO(N)space.
Follow-up questions
- How can you extend the algorithm to produce a concrete schedule mapping each vehicle (
1 .. K) to therequest_ids it serves? Sort requests bypickup_timeand store(return_time, car_id)pairs in a min-heap of currently busy cars. For each booking(pickup_time, return_time, request_id), ifbusy_heapis non-empty andbusy_heap[0][0] <= pickup_time, pop(old_return, car_id)to reuse that car; otherwise allocate a brand-newcar_id = len(assignments) + 1. Appendrequest_idtoassignments[car_id]and push(return_time, car_id)back ontobusy_heap— this runs inO(N log N)time and opens at mostpeakcar IDs. - What changes if every returned vehicle needs
Cunits of maintenance downtime before its next departure? A car returned atreturn_timecannot serve another customer untilreturn_time + C, so simply replacereturn_timewithreturn_time + Cwhen 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: ifkextended intervals[p_i, r_i + C)all contain some instantt, then for any two of them withp_i <= p_jwe havep_j <= t < r_i + C, proving neither booking could finish maintenance in time to serve the other! - Suppose you only own
Mvehicles and may decline bookings. How would you choose a feasible subset of bookings with the largest combined duration? Picking the longest requests greedily fails (forM = 1, taking[0, 10)yields10, whereas taking[0, 6)and[6, 12)yields12). WhenM = 1, this is weighted interval scheduling (sort byreturn_time, binary-search the latest non-overlapping bookingprev[i]withreturn <= pickup_i, and computedp[i] = max(dp[i - 1], duration_i + dp[prev[i]])inO(N log N)time). For generalM > 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 pushesMunits of flow at the smallest total cost): link consecutive unique timestamps with capacity-M, cost-0idle edges, add a capacity-1, cost-(-duration)edge frompickup_timetoreturn_timefor each request, and pushMcars from start to end so at mostMchosen requests overlap at any instant.
Follow-up questions
- How can you extend the algorithm to produce a concrete schedule mapping each vehicle (`1 .. K`) to the `request_id`s it serves?
- What changes if every returned vehicle needs `C` units of maintenance downtime before its next departure?
- Suppose you only own `M` vehicles and may decline bookings. How would you choose a feasible subset of bookings with the largest combined duration?
Similar questions
- Sum Large Integers in Reversed Digit Form
- Alternating Even-Odd Subarray Queries
- Partitioning Grid Plots into Edge-Connected Crop Regions
- Minimum-Fleet Vehicle Allocation for Bookings
- Dynamic Boolean Expression Tree with Leaf Toggles
- Frequency-Based Next-Word Predictor
More Google interview questions
- Minimum Absolute Array Sum Easy
- Nightly Chapter Reading Easy
- Tally Exam Score Tiers Easy Pro
- Minimum Event Chairs Easy Pro
- Dining Waitlist Manager Hard Pro
- Four-Digit PINs with Target Digit Sum Easy Pro
- Filesystem Subtree Byte Usage Medium Pro
- Token Row Score Easy Pro
- Highest-Sum Subarray with Matching Ends Medium Pro
- Navigating an Engineering Project With Open-Ended Requirements Medium Pro