Talentd
FleetCode
Make and follow sheets.Sign in

Last Person to Fit in the Bus solution and explanation

MediumDatabase7 min read70.2% acceptanceUpdated 9 Apr 2026
Last Person to Fit in the Bus | Leetcode 1204 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 10:11 · 12K viewsWatch on YouTube
9 more videos on this problem
  1. Last Person to Fit in the Bus | Leetcode 1204 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 10:11 · 12K views
  2. LeetCode 1204: Last Person to Fit in the Elevator/Bus [SQL]Frederik Müller · 10:26 · 7K views
  3. 35. Last Person to Fit in the Bus | SQL Interview Questions and AnswersStart Practicing · 7:55 · 6K views
  4. LeetCode Medium 1204 Wayfair Interview SQL Question with Detailed ExplanationEveryday Data Science · 10:09 · 6K views
  5. LeetCode SQL Solution | Last Person to Fit in the Bus [Easy Guide]The Engineer's Desk · 3:44 · 1K views
  6. LeetCode - 1204. Last Person to Fit in the Bus (SQL)Chain Of Thought · 7:48 · 585 views
  7. last person to fit in the bus (1204) MS SQL Server programming interview questions on Leetcode.comWeb Reviews · 10:43 · 270 views
  8. 1204 Last Person to Fit in the Bus | Day 69 of 100 Days Of SQL Challenge | LeetCodeEduZy · 14:45 · 160 views
  9. LeetCode 1204 | Last Person to Fit in the Bus | SQL Interview Question Explained!InsightVanta · 5:37 · 150 views
  10. #SQL Leetcode SQL 50 #35: 1204. Last Person to Fit in the BusThe Code Samples · 6:11 · 138 views

The problem

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 1:

Input: 
Queue 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   |
+-------------+
Explanation: The folowing table is ordered by the turn for simplicity.
+------+----+-----------+--------+--------------+
| Turn | ID | Name      | Weight | Total Weight |
+------+----+-----------+--------+--------------+
| 1    | 5  | Alice     | 250    | 250          |
| 2    | 3  | Alex      | 350    | 600          |
| 3    | 6  | John Cena | 400    | 1000         | (last person to board)
| 4    | 2  | Marie     | 200    | 1200         | (cannot board)
| 5    | 4  | Bob       | 175    | ___          |
| 6    | 1  | Winston   | 500    | ___          |
+------+----+-----------+--------+--------------+

Approach overview

Problem Overview: A queue of passengers wants to board a bus with a total weight limit of 1000. Each passenger has a weight and a boarding order (turn). Passengers board sequentially, and once the cumulative weight exceeds the limit, boarding stops. The task is to return the name of the last person who successfully boards without exceeding the capacity.

Approach 1: Sorting and Iterative Weight Accumulation (O(n log n) time, O(1) space)

Start by ordering passengers by their turn value to simulate the real boarding sequence. Then iterate through the list while maintaining a running cumulative weight. For each passenger, add their weight to the total and check whether the sum stays within 1000. The moment the sum would exceed the limit, stop the iteration—the previous passenger is the last one who fits. This approach mirrors how the queue actually behaves and is easy to implement in general programming languages. The main cost comes from sorting the records, making the time complexity O(n log n) with constant extra space.

Approach 2: Direct Database Query with Window Functions (O(n) time, O(1) space)

SQL can solve this more elegantly using a cumulative sum. First sort rows by turn, then compute a running total using a window function like SUM(weight) OVER (ORDER BY turn). This produces the cumulative weight after each passenger boards. Filter rows where the cumulative weight is less than or equal to 1000, and select the passenger with the largest turn. The database engine performs the iteration internally, resulting in an efficient linear scan after ordering. This approach is common in database interview questions involving ordered aggregation and running totals.

The key insight is recognizing that the constraint depends on a prefix sum of weights. Instead of checking combinations, you only track the cumulative weight as passengers board in order. Problems involving sequential accumulation often reduce to prefix sums or running totals, concepts frequently used alongside sorting and analytical queries in database problems.

Recommended for interviews: Interviewers usually expect the SQL window function solution because it demonstrates knowledge of analytical queries and cumulative aggregation. The iterative approach still shows strong problem understanding and is useful when solving the problem in languages like Python or Java where you simulate the queue logic directly.

Approach 1: SQL Query Approach

Given the table name Queue, we can use a SQL query to solve the problem. The key is to sort the rows by the turn column to simulate people boarding the bus in the correct order. Then, we need to compute the cumulative weight as each person boards.

As soon as adding another person's weight exceeds the 1000 kg limit, we know that the last person added was the last allowed on the bus. We can achieve this using a running total and filtering accordingly.

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('''CREATE TABLE Queue (person_id INT, person_name TEXT, weight INT, turn INT)''')
con.executemany('''INSERT INTO Queue (person_id,person_name,weight,turn) VALUES (?,?,?,?)''',
                [(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)])

query = '''
WITH CumulativeWeight AS (
    SELECT person_id, person_name, weight, turn,
           SUM(weight) OVER (ORDER BY turn) AS running_total
    FROM Queue
)
SELECT person_name 
FROM CumulativeWeight
WHERE running_total <= 1000
ORDER BY turn DESC
LIMIT 1;
'''

cursor = con.cursor()
cursor.execute(query)
result = cursor.fetchone()
print(result[0])

This solution uses an in-memory SQLite database to simulate the Queue table. We first insert the given data into the table. The SQL query uses a common table expression (CTE) named CumulativeWeight to compute a running total of the weights as we order by turn.

The cumulative sum is computed using the window function SUM() OVER (ORDER BY turn). The main query then selects the person_name of the last person whose cumulative weight does not exceed 1000 kg, ordered by turn in descending order to get the last safe person.

Complexity

Time Complexity: O(n log n), where n is the number of people, due to sorting.
Space Complexity: O(n) for storing the cumulative weights.

Try this approach in the editor

Approach 2: Approach 1: Sorting and Iterative Weight Accumulation

First, we sort the list of people by their 'turn' values, which indicate the order of boarding. Then, starting from the front of the queue, we keep a cumulative sum of weights as people board. When adding a person's weight causes the total weight to exceed the 1000 kg limit, we stop. The last person added before exceeding the limit is the result.

class Person:
    def __init__(self, person_id, person_name, weight, turn):
        self.person_id = person_id
        self.person_name = person_name
        self.weight = weight
        self.turn = turn


def last_person_to_fit(queue):
    queue.sort(key=lambda x: x.turn)
    total_weight = 0
    for i, person in enumerate(queue):
        if total_weight + person.weight > 1000:
            return queue[i - 1].person_name
        total_weight += person.weight
    return queue[-1].person_name


queue = [Person(5, "Alice", 250, 1), Person(4, "Bob", 175, 5), Person(3, "Alex", 350, 2),
         Person(6, "John Cena", 400, 3), Person(1, "Winston", 500, 6), Person(2, "Marie", 200, 4)]

print(last_person_to_fit(queue))
import java.util.ArrayList;
import java.util.Collections;

class Person implements Comparable<Person> {
    int person_id;
    String person_name;
    int weight;
    int turn;

    Person(int id, String name, int weight, int turn) {
        this.person_id = id;
        this.person_name = name;
        this.weight = weight;
        this.turn = turn;
    }

    @Override
    public int compareTo(Person other) {
        return this.turn - other.turn;
    }
}

public class BusFitting {
    public static String lastPersonToFit(ArrayList<Person> queue) {
        Collections.sort(queue);
        int total_weight = 0;
        for (Person person : queue) {
            if (total_weight + person.weight > 1000) {
                return queue.get(queue.indexOf(person) - 1).person_name;
            }
            total_weight += person.weight;
        }
        return queue.get(queue.size() - 1).person_name;
    }

    public static void main(String[] args) {
        ArrayList<Person> queue = new ArrayList<>();
        queue.add(new Person(5, "Alice", 250, 1));
        queue.add(new Person(4, "Bob", 175, 5));
        queue.add(new Person(3, "Alex", 350, 2));
        queue.add(new Person(6, "John Cena", 400, 3));
        queue.add(new Person(1, "Winston", 500, 6));
        queue.add(new Person(2, "Marie", 200, 4));

        System.out.println(lastPersonToFit(queue));
    }
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Person {
    int person_id;
    string person_name;
    int weight;
    int turn;
};

bool compare(Person a, Person b) {
    return a.turn < b.turn;
}

string lastPersonToFit(vector<Person>& queue) {
    sort(queue.begin(), queue.end(), compare);
    int total_weight = 0;
    for (int i = 0; i < queue.size(); ++i) {
        if (total_weight + queue[i].weight > 1000) {
            return queue[i - 1].person_name;
        }
        total_weight += queue[i].weight;
    }
    return queue.back().person_name;
}

int main() {
    vector<Person> queue = {{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}};
    cout << lastPersonToFit(queue) << endl;
    return 0;
}
class Person {
    constructor(person_id, person_name, weight, turn) {
        this.person_id = person_id;
        this.person_name = person_name;
        this.weight = weight;
        this.turn = turn;
    }
}

function lastPersonToFit(queue) {
    queue.sort((a, b) => a.turn - b.turn);
    let totalWeight = 0;
    for (let i = 0; i < queue.length; i++) {
        if (totalWeight + queue[i].weight > 1000) {
            return queue[i - 1].person_name;
        }
        totalWeight += queue[i].weight;
    }
    return queue[queue.length - 1].person_name;
}

const queue = [
    new Person(5, "Alice", 250, 1),
    new Person(4, "Bob", 175, 5),
    new Person(3, "Alex", 350, 2),
    new Person(6, "John Cena", 400, 3),
    new Person(1, "Winston", 500, 6),
    new Person(2, "Marie", 200, 4)
];

console.log(lastPersonToFit(queue));
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int person_id;
    char person_name[30];
    int weight;
    int turn;
} Person;

int compare(const void *a, const void *b) {
    return ((Person *)a)->turn - ((Person *)b)->turn;
}

char* last_person_to_fit(Person *queue, int n) {
    qsort(queue, n, sizeof(Person), compare);
    int total_weight = 0;
    for (int i = 0; i < n; ++i) {
        if (total_weight + queue[i].weight > 1000) {
            return queue[i - 1].person_name;
        }
        total_weight += queue[i].weight;
    }
    return queue[n - 1].person_name;
}

int main() {
    Person queue[] = {{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}};
    int n = 6;
    printf("%s\n", last_person_to_fit(queue, n));
    return 0;
}
using System;
using System.Collections.Generic;

public class Person {
    public int PersonId { get; set; }
    public string PersonName { get; set; }
    public int Weight { get; set; }
    public int Turn { get; set; }
}

public class Program {
    public static string LastPersonToFit(List<Person> queue) {
        queue.Sort((a, b) => a.Turn.CompareTo(b.Turn));
        int totalWeight = 0;
        for (int i = 0; i < queue.Count; i++) {
            if (totalWeight + queue[i].Weight > 1000) {
                return queue[i - 1].PersonName;
            }
            totalWeight += queue[i].Weight;
        }
        return queue[^1].PersonName;
    }

    public static void Main() {
        List<Person> queue = new List<Person> {
            new Person { PersonId = 5, PersonName = "Alice", Weight = 250, Turn = 1 },
            new Person { PersonId = 4, PersonName = "Bob", Weight = 175, Turn = 5 },
            new Person { PersonId = 3, PersonName = "Alex", Weight = 350, Turn = 2 },
            new Person { PersonId = 6, PersonName = "John Cena", Weight = 400, Turn = 3 },
            new Person { PersonId = 1, PersonName = "Winston", Weight = 500, Turn = 6 },
            new Person { PersonId = 2, PersonName = "Marie", Weight = 200, Turn = 4 }
        };
        Console.WriteLine(LastPersonToFit(queue));
    }
}

In this Python solution, we define a Person class for encapsulating person information. We sort the queue by turn using Python's built-in sort and iterate through the sorted queue accumulating weights till the capacity is breached, thus identifying the last successful boarder.

Complexity

Time Complexity: O(n log n) owing to sorting followed by O(n) for iteration, thereby O(n log n) overall.
Space Complexity: O(1) for space since we only use constant additional storage.

Try this approach in the editor

Approach 3: Approach 2: Direct Database Query

This approach leverages a database operation that uses SQL to determine the last person that can board the bus without exceeding the capacity directly.

SELECT person_name
FROM (
    SELECT person_name, weight,
           SUM(weight) OVER (ORDER BY turn ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as cumulative_weight
    FROM Queue
    ORDER BY turn
) sub
WHERE cumulative_weight <= 1000
ORDER BY cumulative_weight DESC
LIMIT 1;

This SQL query uses a window function to calculate the cumulative weight as people are considered in boarding order ('turn'). It selects the last person for whom the cumulative weight stays within the limit by ordering the cumulative weights and picking the highest.

Complexity

Time Complexity: O(n) for sorting by turn and calculating the cumulative weight.
Space Complexity: O(1), as operations are performed directly on the database.

Try this approach in the editor

Complexity comparison

ApproachComplexity
SQL Query Approach

Time Complexity: O(n log n), where n is the number of people, due to sorting.
Space Complexity: O(n) for storing the cumulative weights.

Approach 1: Sorting and Iterative Weight Accumulation

Time Complexity: O(n log n) owing to sorting followed by O(n) for iteration, thereby O(n log n) overall.
Space Complexity: O(1) for space since we only use constant additional storage.

Approach 2: Direct Database Query

Time Complexity: O(n) for sorting by turn and calculating the cumulative weight.
Space Complexity: O(1), as operations are performed directly on the database.

Complexity analysis

ApproachTimeSpaceWhen to Use
Sorting and Iterative Weight AccumulationO(n log n)O(1)When implementing the logic in general languages like Python, Java, or C++
SQL Window Function (Running Sum)O(n)O(1)Best for database environments where cumulative sums can be computed with window functions

Frequently asked questions

Is Last Person to Fit in the Bus easy or hard?

The problem is rated Medium because the logic is simple but requires recognizing the cumulative constraint. SQL users must know how to apply window functions, while programming solutions require careful simulation of the boarding sequence with prefix sums.

Last Person to Fit in the Bus Python/Java solution

In Python or Java, sort passengers by their turn value and iterate through the list while maintaining a running total of weights. Add each passenger's weight to the cumulative sum and stop when the sum would exceed 1000. The last valid passenger before exceeding the limit is the answer.

How to solve Last Person to Fit in the Bus in O(n)?

Use a cumulative running total with a SQL window function. Compute SUM(weight) OVER (ORDER BY turn) to track the total weight after each passenger boards. Then filter rows where the cumulative sum is ≤ 1000 and return the passenger with the maximum turn among them.

What is the best approach for Last Person to Fit in the Bus?

The most efficient solution uses an SQL window function to compute a cumulative sum of passenger weights ordered by turn. After calculating SUM(weight) OVER (ORDER BY turn), filter rows where the cumulative weight is ≤ 1000 and return the passenger with the largest turn. This directly identifies the last valid passenger in O(n) time after ordering.

Is Last Person to Fit in the Bus asked at Google/Amazon/Meta?

Problems involving window functions, cumulative sums, and ordered aggregations appear frequently in SQL interviews at large tech companies. Variants of this question test familiarity with analytical SQL queries and real-world database data processing patterns.

What data structure is used in Last Person to Fit in the Bus?

The core idea relies on a running cumulative sum rather than a complex data structure. In programming implementations, you iterate through a sorted list and maintain a prefix sum of weights. In SQL, the equivalent concept is implemented with a window function.

What is the time complexity of Last Person to Fit in the Bus?

The SQL window function solution runs in O(n) time for scanning rows once the ordering is applied. The iterative programming approach typically requires sorting by turn first, resulting in O(n log n) time. Both approaches use O(1) additional space.

Comments

Now write it yourselfClose this page and solve Last Person to Fit in the Bus in the editor, without looking.
Practise Last Person to Fit in the Bus