1204. Last Person to Fit in the Bus LeetCode Solution
In this guide, you will get 1204. Last Person to Fit in the Bus LeetCode Solution with the best time and space complexity. The solution to Last Person to Fit in the Bus problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Last Person to Fit in the Bus solution in C++
- Last Person to Fit in the Bus solution in Java
- Last Person to Fit in the Bus solution in Python
- Additional Resources

Problem Statement of Last Person to Fit in the Bus
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.
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.
There is a queue of people waiting to board a bus. However, the bus has a weight limit of 1000 kilograms, so there may be some people who cannot board.
Write a solution to find the person_name of the last person that can fit on the bus without exceeding the weight limit. The test cases are generated such that the first person does not exceed the weight limit.
Note that only one person can board the bus at any given turn.
The result format is in the following example.
Example not found
Constraints not found
Complexity Analysis
- Time Complexity: Google AdSense
- Space Complexity: Google Analytics
1204. Last Person to Fit in the Bus LeetCode Solution in C++
WITH
AccumulatedQueue AS (
SELECT
person_name,
SUM(weight) OVER(ORDER BY turn) AS accumulated_weight
FROM Queue
)
SELECT person_name
FROM AccumulatedQueue
WHERE accumulated_weight <= 1000
ORDER BY accumulated_weight DESC
LIMIT 1;
/* code provided by PROGIEZ */
1204. Last Person to Fit in the Bus LeetCode Solution in Java
N/A
// code provided by PROGIEZ
1204. Last Person to Fit in the Bus LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.