Skip to content
We areTOP 1%

Last Person to Fit in the Bus

MediumLeetCodeSQL: Window Functions
Solve on LeetCode(opens in a new tab)
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews
Hint and exampleShow

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

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account