As reported: Glean Backend Engineer loop (2026), DSA round: "find earliest train route" — the same question was given to other candidates around the same time.
You are given a list of trains. Each train has an id and an itinerary: a list of stops (station, time) with strictly increasing times. You start at station start at time startTime and want to reach destination.
Rules:
- You may wait at any station for as long as you like.
- You can board a train at a station only at the exact time it is there, and only if you are at that station by then.
- Once aboard, you can stay on through its later stops, and get off at any stop.
- At a stop you may transfer to another train that is at the same station at that same time (or any later train there).
Part 1. Return the earliest time you can be at destination, or -1 if it cannot be reached.
Part 2. Return the route itself: the arrival time and an ordered list of steps — start(station, time), wait(station, fromTime, toTime), ride(trainId, fromStation, fromTime, toStation, toTime), and transfer(station, time, fromTrain, toTrain). Merge consecutive waits at one station and consecutive rides on one train into single steps, and insert a transfer whenever the train changes. Any earliest route is accepted; return nothing if the destination is unreachable.
Example 1
T1: A@0 -> B@5 T2: B@5 -> D@8 T3: A@2 -> D@10
start = A, startTime = 0, destination = D -> 8
Ride T1 to B, transfer to T2 at minute 5, arrive at D at 8 (T3 would arrive at 10).
Example 2
T1: A@3 -> C@7 T2: A@1 -> B@4
start = A, startTime = 0, destination = C -> 7
Wait at A until 3 and take T1.
Constraints: times are integers in [0, 10^9]; at most 2 · 10^5 stops in total; a train may have a single stop; if start == destination the answer is startTime.
Code runner format (Part 1): five lines, one JSON value each: stations — for each train, the list of its station names in order; times — for each train, the matching list of times; then start, startTime, destination. Implement earliestArrival(stations, times, start, startTime, destination); the harness prints the time (or -1). Train ids are not needed for Part 1.