Problem
Table: Drivers
|
|
Table: Rides
|
|
Table: AcceptedRides
|
|
Write a solution to report the following statistics for each month of 2020 :
- The number of drivers currently with the Hopper company by the end of the month (
active_drivers
). - The number of accepted rides in that month (
accepted_rides
).
Return the result table ordered by month
in ascending order, where month
is the month’s number (January is 1
, February is 2
, etc.).
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – Monthly Aggregation with Date Functions
Intuition
We need to count, for each month in 2020:
- The number of drivers who joined on or before the end of that month (active_drivers).
- The number of accepted rides requested in that month (accepted_rides).
We can generate all months, then aggregate using date functions and joins.
Approach
- Generate a table of months 1 to 12 for 2020.
- For each month:
- Count drivers whose join_date is on or before the last day of the month.
- Count accepted rides where the ride’s requested_at is in that month and year.
- Use LEFT JOINs to ensure months with zero rides or drivers are included.
- 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.