Bikes Last Time Used — LeetCode 2687 Python Solution

EasyLeetCode PremiumDatabase
Problem
#2687
Reading time
3 min

Table schema

SQL
Table: Bikes +-------------+----------+ | Column Name | Type | +-------------+----------+ | ride_id | int | | bike_number | int | | start_time | datetime | | end_time | datetime | +-------------+----------+ ride_id column contains unique values. Each row contains a ride information that includes ride_id, bike number, start and end time of the ride.

Example

SQL
+-------------+----------+ 
| Column Name | Type     | 
+-------------+----------+ 
| ride_id     | int      | 
| bike_number | int      | 
| start_time  | datetime |
| end_time    | datetime |
+-------------+----------+
ride_id column contains unique values.
Each row contains a ride information that includes ride_id, bike number, start and end time of the ride.
It is guaranteed that start_time and end_time are valid datetime values.

Python solution

Python
import duckdb
import pandas as pd

# Pass input tables as keyword arguments matching the SQL table names.
def solution(**tables) -> pd.DataFrame:
    con = duckdb.connect()
    for name, df in tables.items():
        con.register(name, df)
    return con.execute("""SELECT
    bike_number,
    MAX(end_time) AS end_time
FROM Bikes
GROUP BY bike_number
ORDER BY end_time DESC;""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2687. Bikes Last Time Used?
LeetCode 2687. Bikes Last Time Used is rated Easy on LeetCode.
What topics does LeetCode 2687. Bikes Last Time Used cover?
LeetCode 2687. Bikes Last Time Used is tagged Database on LeetCode.
Is LeetCode 2687. Bikes Last Time Used a premium problem?
Yes. LeetCode 2687. Bikes Last Time Used is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview