[LeetCode] Design Ride Sharing System

3829. Design Ride Sharing System

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

class RideSharingSystem {
deque<int> drivers, riders;
unordered_set<int> cancel;
unordered_set<int> has;
public:
RideSharingSystem() {

}

void addRider(int riderId) {
riders.push_back(riderId);
has.insert(riderId);
}

void addDriver(int driverId) {
drivers.push_back(driverId);
}

vector<int> matchDriverWithRider() {
while(riders.size() and cancel.count(riders[0])) {
cancel.erase(riders[0]);
riders.pop_front();
}
if(drivers.size() == 0 or riders.size() == 0) return {-1,-1};
vector<int> res{drivers[0], riders[0]};
drivers.pop_front();
riders.pop_front();
has.erase(res[1]);
return res;
}

void cancelRider(int riderId) {
if(has.count(riderId)) cancel.insert(riderId);
}
};

/**
* Your RideSharingSystem object will be instantiated and called as such:
* RideSharingSystem* obj = new RideSharingSystem();
* obj->addRider(riderId);
* obj->addDriver(driverId);
* vector<int> param_3 = obj->matchDriverWithRider();
* obj->cancelRider(riderId);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/design-ride-sharing-system/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.