Approach
Depth-first search
For Hopper Company Queries III, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 50 lines of SQL from the credited upstream file 1651.sql.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1WITH RECURSIVE2 Calendar AS (3 SELECT 2 AS MONTH4 UNION ALL5 SELECT MONTH + 16 FROM Calendar7 WHERE MONTH < 118 )9SELECT10 Calendar.month - 1 AS MONTH,11 IFNULL(12 ROUND(13 (14 SELECT SUM(AcceptedRides.ride_distance)15 FROM Rides16 INNER JOIN AcceptedRides17 USING (ride_id)18 WHERE19 YEAR(Rides.requested_at) = '2020'20 AND MONTH(Rides.requested_at) IN (21 Calendar.month - 1,22 Calendar.month,23 Calendar.month + 124 )25 ) / 3,26 227 ),28 029 ) AS average_ride_distance,30 IFNULL(31 ROUND(32 (33 SELECT SUM(AcceptedRides.ride_duration)34 FROM Rides35 INNER JOIN AcceptedRides36 USING (ride_id)37 WHERE38 YEAR(Rides.requested_at) = '2020'39 AND MONTH(Rides.requested_at) IN (40 Calendar.month - 1,41 Calendar.month,42 Calendar.month + 143 )44 ) / 3,45 246 ),47 048 ) AS average_ride_duration49FROM Calendar;50