#1407
Top Travellers
EasyDatabaseHash MapAggregation Functions
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
By using SQL's aggregation functions effectively, we can compute the total distance for each user in a single pass through the Rides table, which is much more efficient than the brute-force method.
⚙️
Algorithm
5 steps- 1Step 1: Use a JOIN operation to combine Users and Rides tables on user_id.
- 2Step 2: Use SUM() to calculate the total distance for each user.
- 3Step 3: Use GROUP BY to group the results by user id.
- 4Step 4: Use ORDER BY to sort the results first by total distance (descending) and then by name (ascending).
- 5Step 5: Return the final result set.
solution.py6 lines
1# Full working Python code
2SELECT u.name, COALESCE(SUM(r.distance), 0) AS travelled_distance
3FROM Users u
4LEFT JOIN Rides r ON u.id = r.user_id
5GROUP BY u.id
6ORDER BY travelled_distance DESC, u.name ASC;ℹ
Complexity note: This complexity is due to a single pass through the Rides table to compute the total distances, making it much more efficient than the brute-force approach.
- 1Using aggregation functions like SUM() can significantly reduce computation time.
- 2LEFT JOIN ensures all users are included even if they have no rides.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.