#262

Trips and Users

Hard
DatabaseHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages SQL's aggregation functions and joins to efficiently calculate the cancellation rates in a single query without needing multiple checks for each trip.

⚙️

Algorithm

4 steps
  1. 1Step 1: Join the Trips table with the Users table for both clients and drivers.
  2. 2Step 2: Filter for unbanned users and the specified date range.
  3. 3Step 3: Use aggregation functions to count total trips and canceled trips in one go.
  4. 4Step 4: Calculate the cancellation rate and round it to two decimal points.
solution.py6 lines
1SELECT DATE(request_at) AS day, ROUND(SUM(CASE WHEN status IN ('cancelled_by_driver', 'cancelled_by_client') THEN 1 ELSE 0 END) / COUNT(*), 2) AS cancellation_rate
2FROM Trips
3JOIN Users AS clients ON Trips.client_id = clients.users_id AND clients.banned = 'No'
4JOIN Users AS drivers ON Trips.driver_id = drivers.users_id AND drivers.banned = 'No'
5WHERE DATE(request_at) BETWEEN '2013-10-01' AND '2013-10-03'
6GROUP BY day;

Complexity note: This complexity is due to the single pass through the Trips and Users tables, allowing us to aggregate results efficiently.

  • 1Understanding how to join tables effectively is crucial.
  • 2Recognizing the importance of filtering out banned users early in the process can simplify calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.