Transit Fleet Simulator: Sampling, Seating Limits, and Fast-Lane Riders
Data Structure DesignModel answerLast updated
Build a bus network simulator: downsample riders by origin-destination pair, board and drop under a capacity cap, validate event logs, and give priority-pass riders precedence.
Transit Fleet Simulator
You are extending a small simulator for a city bus network. Each bus follows a fixed route, and riders show up at stops wanting to reach another stop.
Buses. Each bus has a unique bus_id, a shared seat limit capacity, and a timetable: an ordered list of (time, stop_id) visits.
Riders. Each rider has a unique passenger_id, an appear_time, a from_stop, a to_stop, and a boolean has_priority_pass.
Time is discrete and all times are non-negative integers. Everything fits in memory.
Scale. Up to 100,000 riders, up to 1,000 buses, and up to 1,000 timetable entries per bus.
Core visit rule. When a bus reaches (time, stop_id):
- Every rider on that bus whose
to_stop == stop_idgets off. - Riders waiting at
stop_idwithappear_time <= timewho have never boarded any bus may get on, as long as the bus never holds more thancapacityriders. - The bus's on-board count must be updated after every single board and drop.
All buses start empty. Each event is recorded as a LogEntry(time, bus_id, stop_id, passenger_id, action) with action being "board" or "drop".
Part 1: Shrink the rider population
downsamplePassengers(events, factor) -> List<PassengerEvent>
With 0 < factor <= 1, return about factor * events.size() riders while keeping the mix of (from_stop, to_stop) pairs close to the original. State precisely how you decide which riders to keep.
Part 2: Boarding and dropping with seat limits
simulate(busSchedules, passengers, capacity) -> List<LogEntry>
Process all bus visits in chronological order, applying the visit rule above. Waiting riders board first-come-first-served. Your solution must be fast enough for the stated limits.
Part 3: Check a log
validateLog(log, capacity) -> boolean // or return the first error found
The check must detect at least these problems:
- A bus's occupancy goes below zero.
- A bus's occupancy goes above
capacity. - A rider gets off before getting on.
- A rider boards more than once (on a second bus, or the same bus again).
Describe what state you maintain while scanning and how it changes with each entry.
Part 4: Priority passes
Change the boarding step of Part 2 so that riders with has_priority_pass == true board before those without. Within each group, riders board by appear_time ascending, with ties broken consistently (for example by passenger_id). Capacity must still be strictly respected and counts must stay accurate.
What to deliver
Name the data structures you use for each part, explain why each solution is correct, and give time and space complexity. Mention edge cases you would handle.
Hints
Hint 1
For the sampling part, plain random sampling can lose rare origin-destination pairs. Think about grouping riders by (from_stop, to_stop) and giving each group its own share of the sample, then deciding how to distribute the rounding leftovers.
Hint 2
Do not scan every rider at every bus visit. Flatten all timetables into one sorted list of visits, sort riders by appear_time, and move a pointer forward to release riders into a per-stop waiting structure as time advances. For the bus, store riders bucketed by their destination stop so a drop is a direct lookup.
Hint 3
A min-heap per stop handles both FIFO and priority: use key (appear_time, passenger_id) for plain boarding, and (0 if priority else 1, appear_time, passenger_id) for priority boarding. For the validator, track occupancy per bus, which bus each rider is currently on, and the set of riders who have ever boarded; do not re-sort the log.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
Each part maps to one standard structure:
| Part | Core idea |
|---|---|
| Downsample | Stratified sampling per (from_stop, to_stop) with largest-remainder rounding |
| Simulate | One global sorted list of bus visits, a min-heap of waiting riders per stop, and a per-bus map from destination stop to riders on board |
| Validate | A single linear scan holding per-bus occupancy and per-rider state |
| Priority | Only the heap key changes |
The two things worth stressing are avoiding an O(E) rescan at every visit (there can be up to 10^6 visits) and making the "board at most once" rule fall out of the data structures rather than from an extra check.
Part 1: Stratified downsampling
Uniform random sampling preserves the mix only in expectation, and rare pairs can disappear or be over-represented. Instead:
- Group riders by
(from_stop, to_stop). - Compute each group's exact share
factor * n_gand give it the floor as its quota. - The overall target is
round(factor * E). Distribute the remaining slots to groups with the largest fractional parts (Hamilton / largest-remainder method). The total then matches the target exactly, and each group is within 1 of its proportional share. - Inside each group, choose a uniformly random subset using a seeded RNG so runs are reproducible.
- Sort the result by
(appear_time, passenger_id).
Trade-off: very small groups may still receive a quota of 0. If every pair must appear, force a minimum of 1 and rescale the rest, at the cost of slight distortion. Optionally attach a weight of 1/factor to each kept rider for later metrics.
Parts 2 and 4: Simulation
Ordering. Flatten all timetables into tuples (time, bus_id, stop_id) and sort. Ties on time are broken by bus_id so output is deterministic. Within one bus the original order is preserved (use the index as a final key).
Releasing riders. Sort riders by appear_time. Before handling a visit at time t, advance a pointer and push every rider with appear_time <= t into waiting[from_stop], a min-heap keyed by:
- FIFO mode:
(appear_time, passenger_id) - Priority mode:
(0 if priority else 1, appear_time, passenger_id)
Handling a visit:
- Drop. Pop the list
onboard[bus][stop_id], subtract its length fromcount[bus], and emit a"drop"entry for each rider. This is O(1) per rider; the bus is never scanned. - Board. While
count[bus] < capacityandwaiting[stop]is non-empty, pop the heap, append the rider toonboard[bus][to_stop], incrementcount[bus], and emit"board".
import heapq
from collections import defaultdict
def simulate(buses, riders, capacity, priority=False):
visits = []
for b in buses:
for i, (t, s) in enumerate(b.stops):
visits.append((t, b.bus_id, i, s))
visits.sort()
riders = sorted(riders, key=lambda r: (r.appear_time, r.passenger_id))
waiting = defaultdict(list)
onboard = defaultdict(lambda: defaultdict(list))
count = defaultdict(int)
log, p = [], 0
for t, bus, _, stop in visits:
while p < len(riders) and riders[p].appear_time <= t:
r = riders[p]; p += 1
if r.from_stop == r.to_stop:
continue
rank = 0 if (priority and r.has_priority_pass) else 1
heapq.heappush(waiting[r.from_stop],
(rank, r.appear_time, r.passenger_id, r.to_stop))
for pid in onboard[bus].pop(stop, []):
count[bus] -= 1
log.append((t, bus, stop, pid, "drop"))
h = waiting[stop]
while count[bus] < capacity and h:
_, _, pid, dest = heapq.heappop(h)
onboard[bus][dest].append(pid)
count[bus] += 1
log.append((t, bus, stop, pid, "board"))
return log
In FIFO mode the rank is always 1, so the same code covers Part 2.
Why it is correct
- Capacity: the loop tests
count < capacitybefore each increment, and drops run first so freed seats are reusable at the same stop. - Single boarding: a rider lives in exactly one heap and is removed when boarding, so no later bus can see them.
- Eligibility: a rider enters the heap only once
appear_time <= t, and visit times are non-decreasing. - Priority: heap order is exactly priority first, then arrival time, then id.
- Counts:
countchanges only alongside a log entry.
Part 3: Log validator
Scan in the given order. Do not sort, because drop-before-board within a timestamp matters. State:
occupancy[bus]: current riders on each bus.on_bus[passenger]: the bus a rider is currently on.ever_boarded: set of riders who have boarded at any time.
Checks per entry:
- board: fail if the rider is in
ever_boarded(double boarding or two buses); fail ifoccupancy + 1 > capacity. Otherwise record them and increment. - drop: fail if the rider is not in
on_bus(drop before boarding or double drop); fail if they are on a different bus; fail if occupancy would go below zero. Otherwise remove and decrement. - Any other action is an error.
Return the first error with its index; this is far more useful for debugging than a bare boolean.
Complexity
Let A be the number of visits (up to 10^6), E the riders (up to 10^5), and L the log length.
| Function | Time | Space |
|---|---|---|
| Downsample | O(E log E) including the final sort | O(E) |
| Simulate | O(A log A + E log E); drops are O(1) per rider | O(A + E) |
| Validate | O(L) | O(E + B) |
Edge cases and common mistakes
- Riders with
from_stop == to_stopshould be filtered out. - Capacity 0 means nobody boards and the log has no entries.
- Two buses at the same stop and time: the lower
bus_idboards first, by the tie-break. - A bus revisiting a stop works naturally because drops are bucketed by stop.
- A rider whose destination never appears later on the bus's route stays on board; a production version could refuse to board such riders.
- Common mistakes: scanning all riders at each visit, boarding before dropping, re-sorting the log in the validator, and enforcing "board once" with a separate pass instead of structurally.