Hopper Company Queries II — LeetCode 1645 Python Solution
HardLeetCode PremiumDatabase
- Problem
- #1645
- Reading time
- 8 min
- Source
- leetcode.com
Table schema
SQL
Table: Drivers +-------------+---------+ | Column Name | Type | +-------------+---------+ | driver_id | int | | join_date | date | +-------------+---------+ driver_id is the column with unique values for this table. Each row of this table contains the driver's ID and the date they joined the Hopper company.Example
SQL
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| driver_id | int |
| join_date | date |
+-------------+---------+
driver_id is the column with unique values for this table.
Each row of this table contains the driver's ID and the date they joined the Hopper company.Python solution
Python
import duckdb
import pandas as pd
def solution(drivers: pd.DataFrame, rides: pd.DataFrame, accepted_rides: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Drivers", drivers)
con.register("Rides", rides)
con.register("AcceptedRides", accepted_rides)
return con.execute("""WITH RECURSIVE
Month AS (
SELECT 1 AS month
UNION
SELECT month + 1
FROM Month
WHERE month < 12
),
S AS (
SELECT month, driver_id, join_date
FROM
Month AS m
LEFT JOIN Drivers AS d
ON YEAR(d.join_date) < 2020
OR (YEAR(d.join_date) = 2020 AND MONTH(d.join_date) <= month)
),
T AS (
SELECT driver_id, requested_at
FROM
Rides
JOIN AcceptedRides USING (ride_id)
WHERE YEAR(requested_at) = 2020
)
SELECT
month,
IFNULL(
ROUND(COUNT(DISTINCT t.driver_id) * 100 / COUNT(DISTINCT s.driver_id), 2),
0
) AS working_percentage
FROM
S AS s
LEFT JOIN T AS t
ON s.driver_id = t.driver_id
AND s.join_date <= t.requested_at
AND s.month = MONTH(t.requested_at)
GROUP BY 1;""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1645. Hopper Company Queries II?
- LeetCode 1645. Hopper Company Queries II is rated Hard on LeetCode.
- What topics does LeetCode 1645. Hopper Company Queries II cover?
- LeetCode 1645. Hopper Company Queries II is tagged Database on LeetCode.
- Is LeetCode 1645. Hopper Company Queries II a premium problem?
- Yes. LeetCode 1645. Hopper Company Queries II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.