Last Person to Fit in the Bus - Problem

You are given a table Queue representing people waiting to board a bus. The bus has a weight limit of 1000 kilograms.

Each person has:

  • person_id - unique identifier
  • person_name - name of the person
  • weight - weight in kilograms
  • turn - boarding order (1 = first to board)

Write a SQL query to find the name of the last person who can board the bus without exceeding the weight limit of 1000kg.

Note: People board in order of their turn value, and the first person is guaranteed to fit on the bus.

Table Schema

Queue
Column Name Type Description
person_id PK int Unique identifier for each person
person_name varchar Name of the person
weight int Weight of person in kilograms
turn int Boarding order (1 = first, n = last)
Primary Key: person_id
Note: Turn values range from 1 to n where n is total number of people

Input & Output

Example 1 — Basic Bus Loading
Input Table:
person_id person_name weight turn
5 Alice 250 1
4 Bob 175 5
3 Alex 350 2
6 John Cena 400 3
1 Winston 500 6
2 Marie 200 4
Output:
person_name
John Cena
💡 Note:

When ordered by turn: Alice (250) → Alex (350) → John Cena (400) → Marie (200) → Bob (175) → Winston (500). Cumulative weights: 250 → 600 → 1000 → 1200. John Cena is the last person whose cumulative weight (1000kg) doesn't exceed the limit.

Example 2 — Early Weight Limit
Input Table:
person_id person_name weight turn
1 Alice 800 1
2 Bob 175 2
3 Charlie 80 3
Output:
person_name
Bob
💡 Note:

Cumulative weights in order: Alice (800) → Bob (975) → Charlie (1055). Since Charlie would exceed 1000kg, Bob is the last person who can board.

Constraints

  • 1 ≤ n ≤ 1000 where n is the number of people
  • 1 ≤ person_id ≤ n
  • 1 ≤ weight ≤ 1000
  • 1 ≤ turn ≤ n
  • All person_id and turn values are unique
  • The first person (turn=1) will not exceed the weight limit

Visualization

Tap to expand
Last Person to Fit in Bus (1000kg limit)Queue TablenameweightturnAlice2501Alex3502John4003Marie2004RunningTotalCumulative WeightsnameturncumulativestatusAlice1250✓ FitsAlex2600✓ FitsJohn31000✓ LASTMarie41200✗ OverResultJohn CenaLast person under 1000kg limit
Understanding the Visualization
1
Input
Queue table with people and weights
2
Calculate
Running sum of weights by turn order
3
Filter
Last person under 1000kg limit
Key Takeaway
🎯 Key Insight: Use window functions to calculate running totals and filter by business constraints
Asked in
Amazon 15 Microsoft 12 Google 8
28.5K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen