Design a Dispatch Queue for Autonomous Taxi Requests
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate an event-driven dispatching system that maintains pending requests ordered by pickup time and processes state updates efficiently using heaps and hash maps.
You are asked to build the core dispatch engine for an automated transport fleet. The system handles ride booking requests, cancellations, periodic state progression based on time, and querying current pending requests.
Implement a function ride_scheduler(operations: List[str], arguments: List[List]) -> List that receives a sequence of command names alongside their respective argument lists and executes them in sequential order. Return a list containing the output of each command in the order they were executed.
The supported operations are:
add_ride(ride_id: str, pickup_time: int, location: str)Registers a request identified byride_idwith a scheduledpickup_time(seconds) and location string. Overwrites any existing request matchingride_id. ReturnsNone.cancel_ride(ride_id: str)Cancels the active request with the specifiedride_id. Ifride_idis unknown or the ride has already started, no action is taken. ReturnsNone.process_events(current_time: int)Advances system state up to timestampcurrent_time. All pending rides scheduled at or beforecurrent_time(pickup_time <= current_time) transition to started and are no longer pending. ReturnsNone.get_pending_rides()Returns a list ofride_idstrings for all currently active, non-started requests. The list must be ordered primarily bypickup_timein ascending order. When timestamps tie, break ties lexicographically byride_id.
Constraints
- $1 \le \text{len(operations)} \le 10^4$
pickup_timeandcurrent_timeare non-negative integers ($\le 10^9$).ride_idandlocationare non-empty strings.- Timestamps passed into
process_eventsmay not be strictly increasing. Ifcurrent_timeis less than a previously processed timestamp, no new rides are processed.
Examples
Example 1
Input: ride_scheduler(['add_ride', 'add_ride', 'get_pending_rides', 'process_events', 'get_pending_rides'], [['ride_1', 100, 'Point A'], ['ride_2', 50, 'Point B'], [], [75], []])
Output: [None, None, ['ride_2', 'ride_1'], None, ['ride_1']]
Example 2
Input: ride_scheduler(['add_ride', 'add_ride', 'get_pending_rides', 'process_events', 'get_pending_rides'], [['a', 10, 'X'], ['b', 10, 'Y'], [], [10], []])
Output: [None, None, ['a', 'b'], None, []]
Example 3
Input: ride_scheduler(['add_ride', 'add_ride', 'cancel_ride', 'get_pending_rides'], [['late', 20, 'A'], ['early', 5, 'B'], ['early'], []])
Output: [None, None, None, ['late']]
Hints
Hint 1
Use a combination of a min-heap for ordered time processing and a dictionary to maintain the ground truth of pending rides.
Hint 2
When a ride is canceled or updated with a new scheduled time, avoid searching the min-heap. Use lazy deletion instead by ignoring invalidated heap records during processing.
Hint 3
For `get_pending_rides()`, construct the list by sorting the active records from your ground-truth dictionary by primary key `pickup_time` and secondary key `ride_id`.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To satisfy the performance requirements, we pair two complementary data structures:
- Hash Table (
pending): Mapsride_idto its latest active(pickup_time, location). This serves as the source of truth for whether a ride is currently pending and what its current pickup time is. - Min-Heap (
heap): Stores(pickup_time, ride_id)tuples sorted by time. This allows us to quickly identify due events without scanning all entries.
Lazy Deletion Pattern
Removing items directly from a min-heap takes $O(N)$ time. Instead, we perform lazy deletion:
add_ride: Insert/update the record inpendingand push(pickup_time, ride_id)intoheap.cancel_ride: Removeride_idfrompending. We do not update the heap immediately.process_events: Repeatedly pop entries fromheapwherepickup_time <= current_time. A popped entry is valid only ifride_idexists inpendingand its recordedpickup_timematches the popped timestamp. If valid, remove it frompending(marking it as started). Stale or canceled entries are simply ignored and discarded.get_pending_rides: Extract live entries directly frompending, sort them by(pickup_time, ride_id), and return the extracted IDs.
Complexity Analysis
- Time Complexity:
add_ride: $O(\log N)$ for pushing to the min-heap.cancel_ride: $O(1)$ dictionary lookup and deletion.process_events: $O(K \log N)$ where $K$ is the number of heap elements popped. Each pushed entry is popped at most once across the execution lifecycle.get_pending_rides: $O(P \log P)$ where $P$ is the number of active pending rides at query time.
- Space Complexity: $O(N)$ where $N$ is the total number of ride operations, as each added ride occupies space in memory until popped from the heap.
import heapq
from typing import List
def ride_scheduler(operations: List[str], arguments: List[List]) -> List:
pending = {}
heap = []
results = []
for operation, args in zip(operations, arguments):
if operation == "add_ride":
ride_id, pickup_time, location = args
pending[ride_id] = (pickup_time, location)
heapq.heappush(heap, (pickup_time, ride_id))
results.append(None)
elif operation == "cancel_ride":
ride_id = args[0]
pending.pop(ride_id, None)
results.append(None)
elif operation == "process_events":
current_time = args[0]
while heap and heap[0][0] <= current_time:
pickup_time, ride_id = heapq.heappop(heap)
record = pending.get(ride_id)
if record is not None and record[0] == pickup_time:
del pending[ride_id]
results.append(None)
elif operation == "get_pending_rides":
rides = sorted((pickup_time, ride_id) for ride_id, (pickup_time, _) in pending.items())
results.append([ride_id for _, ride_id in rides])
else:
raise ValueError(f"unknown operation: {operation}")
return results