Last Person to Fit in the Bus
MediumLeetCodeSQL: Window Functions
Hint and exampleShowHide
Compute a running total with SUM(...) OVER (ORDER BY ...), keep the rows whose running total stays within the limit, and take the last of them.
Example: lift(name, turn, weight) with a limit of 200
name | turn | weight
Asha | 1 | 70
Ravi | 2 | 90
Meera | 3 | 60
SELECT name
FROM (
SELECT name, turn,
SUM(weight) OVER (ORDER BY turn) AS total
FROM lift
) t
WHERE total <= 200
ORDER BY turn DESC
LIMIT 1; -- running totals 70, 160, 220, so returns Ravi
More in SQL: Window Functions
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the difference between ROW_NUMBER, RANK and DENSE_RANK? | Concept | Easy | Read the answer to What is the difference between ROW_NUMBER, RANK and DENSE_RANK? | |||
| 2 | Rank Scores | LeetCode | Medium | Solve Rank Scores on LeetCode (opens in a new tab) | |||
| 3 | Consecutive Numbers | LeetCode | Medium | Solve Consecutive Numbers on LeetCode (opens in a new tab) | |||
| 4 | Last Person to Fit in the Bus | LeetCode | Medium | Solve Last Person to Fit in the Bus on LeetCode (opens in a new tab) | |||
| 5 | Restaurant Growth | LeetCode | Medium | Solve Restaurant Growth on LeetCode (opens in a new tab) | |||
| 6 | Department Top Three Salaries | LeetCode | Hard | Solve Department Top Three Salaries on LeetCode (opens in a new tab) |