#3829
Medium Algorithms Design ride sharing system
Hash Table Design Queue Data Stream
63.4% acceptance
Mar 16, 2026
52
5
A ride sharing system manages ride requests from riders and availability from drivers. Riders request rides, and drivers become available over time. The system should match riders and drivers in the order they arrive.
Implement the RideSharingSystem class:
RideSharingSystem() Initializes the system.
void addRider(int riderId) Adds a new rider with the given riderId.
void addDriver(int driverId) Adds a new driver with the given driverId.
int[] matchDriverWithRider() Matches the earliest available driver with the earliest waiting rider and removes both of them from the system. Returns an integer array of size 2 where result = [driverId, riderId] if a match is made. If no match is available, returns [-1, -1].
void cancelRider(int riderId) Cancels the ride request of the rider with the given riderId if the rider exists and has not yet been matched.
Solution
Rust
Time O(n)
Space O(n)
use std::collections::{VecDeque, HashSet};
struct RideSharingSystem {
riders: VecDeque<i32>,
drivers: VecDeque<i32>,
active_riders: HashSet<i32>,
}
impl RideSharingSystem {
fn new() -> Self {
RideSharingSystem {
riders: VecDeque::new(),
drivers: VecDeque::new(),
active_riders: HashSet::new(),
}
}
fn add_rider(&mut self, rider_id: i32) {
self.active_riders.insert(rider_id);
self.riders.push_back(rider_id);
}
fn add_driver(&mut self, driver_id: i32) {
self.drivers.push_back(driver_id);
}
fn match_driver_with_rider(&mut self) -> Vec<i32> {
// Skip riders that were cancelled
while let Some(&front) = self.riders.front() {
if !self.active_riders.contains(&front) {
self.riders.pop_front();
} else {
break;
}
}
if self.riders.is_empty() || self.drivers.is_empty() {
return vec![-1, -1];
}
let driver = self.drivers.pop_front().unwrap();
let rider = self.riders.pop_front().unwrap();
self.active_riders.remove(&rider);
vec![driver, rider]
}
fn cancel_rider(&mut self, rider_id: i32) {
// Only cancel if the rider is currently active (exists in the system)
self.active_riders.remove(&rider_id);
}
}