1204. Last Person to Fit in the Bus
SQL 50 · Advanced Select and Joins (day 5). Decode it with the hints, solve it on LeetCode, then compare with the reference solution in MySQLPostgreSQL.
Your work
Hints
Open one at a time. Try to finish with as few as you can.
1. What does one output row represent?
One person.
2. Approach
SUM(weight) OVER (ORDER BY turn) in a CTE, keep total <= 1000, ORDER BY turn DESC LIMIT 1.
3. The trap
Order the running sum by turn, not by id.
Reference solution
Tested on MySQL 8.0 and PostgreSQL 16. Switch dialect at the top of the page.
Show the MySQLPostgreSQL solution
WITH q AS (
SELECT person_name, turn,
SUM(weight) OVER (ORDER BY turn) AS total
FROM Queue
)
SELECT person_name
FROM q
WHERE total <= 1000
ORDER BY turn DESC
LIMIT 1;