You are given two tables: Buses and Passengers.
The Buses table contains information about buses arriving at the LeetCode station, including their bus_id, arrival_time, and capacity (number of empty seats).
The Passengers table contains information about passengers arriving at the station with their passenger_id and arrival_time.
Bus Assignment Rules:
- A passenger can board a bus if the passenger's arrival time is less than or equal to the bus's arrival time
- Passengers board the earliest available bus that they are eligible for
- Each bus has a limited
capacity- if more passengers are waiting than the bus can hold, only the firstcapacitypassengers (by arrival time) will board - Once a passenger boards a bus, they cannot board another bus
Write a SQL query to find the number of passengers that boarded each bus. Return the result ordered by bus_id in ascending order.
Table Schema
| Column Name | Type | Description |
|---|---|---|
bus_id
PK
|
int | Unique identifier for each bus |
arrival_time
|
int | Time when the bus arrives at the station |
capacity
|
int | Number of empty seats available on the bus |
| Column Name | Type | Description |
|---|---|---|
passenger_id
PK
|
int | Unique identifier for each passenger |
arrival_time
|
int | Time when the passenger arrives at the station |
Input & Output
| bus_id | arrival_time | capacity |
|---|---|---|
| 1 | 4 | 1 |
| 3 | 5 | 2 |
| passenger_id | arrival_time |
|---|---|
| 11 | 1 |
| 12 | 2 |
| 13 | 6 |
| bus_id | passengers_cnt |
|---|---|
| 1 | 1 |
| 3 | 2 |
Passenger 11 arrives at time 1 and can board bus 1 (arrives at time 4). Passenger 12 arrives at time 2 and can board bus 3 (arrives at time 5) since bus 1 is full. Passenger 13 arrives at time 6, after both buses have left, so cannot board any bus.
| bus_id | arrival_time | capacity |
|---|---|---|
| 1 | 3 | 2 |
| 2 | 6 | 1 |
| passenger_id | arrival_time |
|---|---|
| 11 | 7 |
| bus_id | passengers_cnt |
|---|---|
| 1 | 0 |
| 2 | 0 |
Passenger 11 arrives at time 7, which is after both buses have already left (bus 1 at time 3, bus 2 at time 6). Therefore, no passengers board any bus.
Constraints
-
1 ≤ Buses.bus_id, Passengers.passenger_id ≤ 1000 -
1 ≤ Buses.arrival_time, Passengers.arrival_time ≤ 1000000 -
1 ≤ Buses.capacity ≤ 1000000 -
All
bus_idvalues are unique -
All
passenger_idvalues are unique - No two buses arrive at the same time