In a ride-sharing service, we have a database table Rides that tracks all completed trips. Each row represents a single ride with three key pieces of information:
ride_id- unique identifier for each ridedriver_id- ID of the person who drovepassenger_id- ID of the person who was the passenger
Your task: Some people in the system act as both drivers and passengers at different times. We need to find out for each person who has been a driver, how many times they have also been a passenger in other rides.
Output format: Return a result table with two columns:
driver_id- ID of each drivercnt- number of times that driver was also a passenger
Note: If a driver has never been a passenger, they should still appear in the result with a count of 0.
Input & Output
Visualization
Time & Space Complexity
Single pass through data with efficient join operations, typically O(n log n) due to internal sorting for GROUP BY
Space for result set plus temporary space for join operations
Constraints
- 1 โค rides.length โค 104
- 1 โค ride_id, driver_id, passenger_id โค 106
- driver_id โ passenger_id for each ride
- ride_id values are unique