Problem
Table: Drivers
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| driver_id | int |
| name | varchar |
| age | int |
| experience | int |
| accidents | int |
+--------------+---------+
(driver_id) is the unique key for this table.
Each row includes a driver's ID, their name, age, years of driving experience, and the number of accidents they've had.
Table: Vehicles
+--------------+---------+
| vehicle_id | int |
| driver_id | int |
| model | varchar |
| fuel_type | varchar |
| mileage | int |
+--------------+---------+
(vehicle_id, driver_id, fuel_type) is the unique key for this table.
Each row includes the vehicle's ID, the driver who operates it, the model, fuel type, and mileage.
Table: Trips
+--------------+---------+
| trip_id | int |
| vehicle_id | int |
| distance | int |
| duration | int |
| rating | int |
+--------------+---------+
(trip_id) is the unique key for this table.
Each row includes a trip's ID, the vehicle used, the distance covered (in miles), the trip duration (in minutes), and the passenger's rating (1-5).
Uber is analyzing drivers based on their trips. Write a solution to find the top-performing driver for each fuel type based on the following criteria:
- A driver’s performance is calculated as the average rating across all their trips. Average rating should be rounded to
2
decimal places. - If two drivers have the same average rating, the driver with the longer total distance traveled should be ranked higher.
- If there is still a tie , choose the driver with the fewest accidents.
Return the result table ordered by fuel_type
inascending order.
The result format is in the following example.
Example 1:
|
|
Solution
Method 1 – SQL: Ranking and Filtering
Intuition
A top performing driver is one with the highest experience and the fewest accidents. We can use window functions to rank drivers by experience (descending) and accidents (ascending), then select those with both the highest experience and the lowest accidents.
Approach
- Use window functions to find the maximum experience and minimum accidents among all drivers.
- Select drivers whose experience equals the maximum and accidents equals the minimum.
- Return their driver_id and name.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— n = number of drivers. - 🧺 Space complexity:
O(n)
— For storing intermediate results.