#3829
Design Ride Sharing System
MediumHash TableDesignQueueData StreamQueueData Stream
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using queues allows us to efficiently manage the order of riders and drivers, ensuring quick matching and cancellations.
⚙️
Algorithm
3 steps- 1Step 1: Use two queues to store riders and drivers.
- 2Step 2: When matching, dequeue the first rider and driver if both are available.
- 3Step 3: For cancellation, remove the rider from the queue efficiently.
solution.py15 lines
1from collections import deque
2class RideSharingSystem:
3 def __init__(self):
4 self.riders = deque()
5 self.drivers = deque()
6 def addRider(self, riderId):
7 self.riders.append(riderId)
8 def addDriver(self, driverId):
9 self.drivers.append(driverId)
10 def matchDriverWithRider(self):
11 if self.riders and self.drivers:
12 return [self.drivers.popleft(), self.riders.popleft()]
13 return [-1, -1]
14 def cancelRider(self, riderId):
15 self.riders = deque([r for r in self.riders if r != riderId])ℹ
Complexity note: The complexity is linear due to efficient queue operations for adding, matching, and canceling riders and drivers.
- 1Using queues preserves order for matching.
- 2Efficient cancellation requires a structure that supports quick removal.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.