Google questions

Train Schedule Reachability

GooglePhone screenMedium

A timetable is a list of legs. Each leg is [start, end, depart, arrive]: a train from station start to station end that departs at time depart and arrives at time arrive, with depart < arrive. Each leg can be taken at most once, at its stated times. You start at station source at time 0. After arriving somewhere at time t, you can board any leg from that station whose depart is at least t, so a leg leaving the very minute you arrive is allowed.

Part 1: Reachable destination

You are given a timetable of legs as described above, a source station, and a destination station. Return True if you can travel from source to destination using the legs, starting at time 0, and False otherwise.

If source equals destination, return True without taking any leg. The legs are given in no particular order.

  1. Example 1
    legs
    [["A","Y",1,20],["A","Y",2,5],["Y","B",6,9]]
    source
    "A"
    destination
    "B"
    Output
    true

    Why: The leg arriving at Y at time 20 is too late to catch the Y to B train. Taking the leg that arrives at Y at time 5 allows boarding the leg departing at 6, reaching B.

  2. Example 2
    legs
    [["A","B",1,2]]
    source
    "A"
    destination
    "A"
    Output
    true

    Why: The start station and the destination are both A, so the trip is already complete without boarding any leg. The result is true.

Constraints

  • 0 <= len(legs) <= 10^5
  • 0 <= legs[i][2] < legs[i][3] <= 10^9
  • 1 <= len(legs[i][0]) <= 10
  • 1 <= len(legs[i][1]) <= 10
  • 1 <= len(source) <= 10
  • 1 <= len(destination) <= 10
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question