Last Person to Fit in the Bus — LeetCode 1204 Python Solution
MediumDatabase
- Problem
- #1204
- Reading time
- 3 min
- Source
- leetcode.com
Table schema
SQL
Table: Queue +-------------+---------+ | Column Name | Type | +-------------+---------+ | person_id | int | | person_name | varchar | | weight | int | | turn | int | +-------------+---------+ person_id column contains unique values. This table has the information about all people waiting for a bus.Example
SQL
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| person_id | int |
| person_name | varchar |
| weight | int |
| turn | int |
+-------------+---------+
person_id column contains unique values.
This table has the information about all people waiting for a bus.
The person_id and turn columns will contain all numbers from 1 to n, where n is the number of rows in the table.
turn determines the order of which the people will board the bus, where turn=1 denotes the first person to board and turn=n denotes the last person to board.
weight is the weight of the person in kilograms.Python solution
Python
import duckdb
import pandas as pd
def solution(queue: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Queue", queue)
return con.execute("""SELECT a.person_name
FROM
Queue AS a,
Queue AS b
WHERE a.turn >= b.turn
GROUP BY a.person_id
HAVING SUM(b.weight) <= 1000
ORDER BY a.turn DESC
LIMIT 1;""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1204. Last Person to Fit in the Bus?
- LeetCode 1204. Last Person to Fit in the Bus is rated Medium on LeetCode.
- What topics does LeetCode 1204. Last Person to Fit in the Bus cover?
- LeetCode 1204. Last Person to Fit in the Bus is tagged Database on LeetCode.