Problem
Table: Drivers
|
|
Table: Rides
|
|
Table: AcceptedRides
|
|
Write a solution to report the percentage of working drivers (working_percentage
) for each month of 2020 where:
$$ percentage_{month} = \frac{\text{\# drivers that accepted at least one ride during the month}}{\text{\# available drivers during the month}} \times 100 $$
Note that if the number of available drivers during a month is zero, we consider the working_percentage
to be 0
.
Return the result table ordered by month
in ascending order, where month
is the month’s number (January is 1
, February is 2
, etc.). Round working_percentage
to the nearest 2 decimal places.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – Monthly Aggregation and Unique Driver Count
Intuition
For each month in 2020, we need to:
- Count the number of drivers who joined on or before the end of the month (active drivers).
- Count the number of unique drivers who accepted at least one ride requested in that month (working drivers).
- Compute the working percentage as (working drivers / active drivers) * 100, rounded to two decimal places. If there are no active drivers, the percentage is 0.
Approach
- Generate a table of months 1 to 12 for 2020.
- For each month:
- Find the last day of the month.
- Count drivers whose join_date is on or before the last day (active drivers).
- Find all rides requested in that month, and from those, count unique driver_ids in AcceptedRides (working drivers).
- Compute the percentage as described.
- Return the result ordered by month.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(12N + 12M)
, where N is the number of drivers and M is the number of rides, since we scan all drivers and rides for each month. - 🧺 Space complexity:
O(1)
(excluding output), as we only store counts per month.