fork download
  1. /*
  2. PROBLEM:
  3. Reach a Destination Through Scheduled Flights
  4.  
  5. Given a list of flights:
  6. [origin, destination, departureTime, arrivalTime]
  7.  
  8. Determine whether we can reach targetAirport from
  9. startAirport, starting at time 0.
  10.  
  11. A connecting flight is valid if:
  12. departureTime >= currentArrivalTime.
  13.  
  14.  
  15. APPROACH: Sorting + Greedy Earliest Arrival
  16.  
  17. 1. If startAirport === targetAirport, return true.
  18.  
  19. 2. Sort all flights by departure time in ascending order.
  20.  
  21. 3. Maintain an earliest array, where earliest[i]
  22.   represents the earliest known time at which we
  23.   can reach airport i.
  24.  
  25. 4. Initialize all arrival times to Infinity,
  26.   except earliest[startAirport] = 0.
  27.  
  28. 5. Iterate through the sorted flights.
  29.  
  30.   For each flight, check:
  31.   a. Can we reach the origin before or exactly
  32.   when the flight departs?
  33.  
  34.   b. Does this flight provide an earlier arrival
  35.   time at the destination?
  36.  
  37.   If both conditions are satisfied, update
  38.   earliest[destination].
  39.  
  40. 6. Return whether earliest[targetAirport] is finite.
  41.  
  42.  
  43. WHY DOES THIS WORK?
  44.  
  45. For any two valid connecting flights A and B:
  46.  
  47. departureA < arrivalA <= departureB
  48.  
  49. Therefore:
  50. departureA < departureB
  51.  
  52. Sorting by departure time ensures that prerequisite
  53. flights are always processed before connecting flights.
  54.  
  55. Also, arriving earlier at an airport is always
  56. at least as good as arriving later because we can wait.
  57.  
  58.  
  59. TIME COMPLEXITY: O(V + E log E)
  60.  
  61. V = Number of airports
  62. E = Number of flights
  63.  
  64. - Sorting flights: O(E log E)
  65. - Initializing earliest array: O(V)
  66. - Iterating through flights: O(E)
  67. - Checking and updating each flight: O(1)
  68.  
  69. Total:
  70. O(E log E + V + E)
  71. = O(V + E log E)
  72.  
  73. If flights are already sorted:
  74. O(V + E)
  75.  
  76.  
  77. SPACE COMPLEXITY: O(V + E)
  78.  
  79. - Earliest arrival array: O(V)
  80. - Temporary variables: O(1)
  81. - Sorting auxiliary space: O(E), assuming
  82.   a sorting implementation such as V8's TimSort.
  83.  
  84. Excluding sorting space: O(V)
  85.  
  86. NOTE:
  87. This implementation sorts the input flights array
  88. in place.
  89. */
  90.  
  91. /*
  92. WHY DO WE SORT FLIGHTS BY DEPARTURE TIME?
  93.  
  94. If we don't sort by departure time, we might process
  95. a flight with a higher departure time before processing
  96. a flight with a smaller departure time.
  97.  
  98. That earlier flight might have helped us reach the
  99. origin airport in time to catch the later flight.
  100.  
  101. However, since we have already processed and skipped
  102. the later flight, we would have to revisit it.
  103.  
  104. By sorting flights in ascending order of departure time,
  105. we ensure that whenever we process a flight, we have
  106. already considered all flights with smaller departure
  107. times.
  108.  
  109. Therefore, if earliest[origin] > departure, we can
  110. confidently skip the current flight because no
  111. unprocessed flight can help us reach its origin
  112. in time to catch it.
  113.  
  114.  
  115. EXAMPLE:
  116.  
  117. airportCount = 3
  118. startAirport = 0
  119. targetAirport = 2
  120.  
  121. flights = [
  122.   [1, 2, 5, 8],
  123.   [0, 1, 2, 4]
  124. ];
  125.  
  126. Airport graph:
  127.  
  128.   dep: 2 dep: 5
  129.   arr: 4 arr: 8
  130.   0 ----------> 1 ----------> 2
  131.  
  132.  
  133. CASE 1: WITHOUT SORTING
  134.  
  135. Initially:
  136. earliest = [0, Infinity, Infinity]
  137.  
  138. Process flight [1, 2, 5, 8]:
  139.  
  140. earliest[1] <= 5
  141. Infinity <= 5 --> false
  142.  
  143. We haven't reached airport 1 yet.
  144. Therefore, we skip this flight.
  145.  
  146. Process flight [0, 1, 2, 4]:
  147.  
  148. earliest[0] <= 2
  149. 0 <= 2 --> true
  150.  
  151. Update earliest[1] = 4.
  152.  
  153. earliest = [0, 4, Infinity]
  154.  
  155. Now we have reached airport 1 in time to catch
  156. the flight departing at time 5.
  157.  
  158. However, we have already processed that flight.
  159.  
  160. The loop ends and returns false, which is incorrect.
  161.  
  162. We would need to revisit the previously skipped flight.
  163.  
  164.  
  165. CASE 2: WITH SORTING
  166.  
  167. Sort flights by departure time:
  168.  
  169. flights = [
  170.   [0, 1, 2, 4],
  171.   [1, 2, 5, 8]
  172. ];
  173.  
  174. Initially:
  175. earliest = [0, Infinity, Infinity]
  176.  
  177. Process flight [0, 1, 2, 4]:
  178.  
  179. earliest[0] <= 2
  180. 0 <= 2 --> true
  181.  
  182. Update earliest[1] = 4.
  183.  
  184. earliest = [0, 4, Infinity]
  185.  
  186. Process flight [1, 2, 5, 8]:
  187.  
  188. earliest[1] <= 5
  189. 4 <= 5 --> true
  190.  
  191. Update earliest[2] = 8.
  192.  
  193. earliest = [0, 4, 8]
  194.  
  195. earliest[targetAirport] !== Infinity
  196.  
  197. Return true.
  198.  
  199.  
  200. KEY TAKEAWAY:
  201.  
  202. Sorting by departure time ensures that all potentially
  203. useful earlier flights are processed before the current
  204. flight.
  205.  
  206. If we cannot catch the current flight even with the
  207. earliest possible arrival at its origin, no remaining
  208. flight can help us catch it.
  209.  
  210. This allows us to process every flight exactly once
  211. after sorting, without revisiting any previous flight.
  212.  
  213. This works because every flight has a strictly positive
  214. duration (departureTime < arrivalTime).
  215. */
  216. // ==================== SOLUTION ====================
  217.  
  218. function canReachDestination(
  219. airportCount, flights, startAirport, targetAirport
  220. ) {
  221. if (startAirport === targetAirport) return true;
  222.  
  223. // Sort flights by departure time
  224. flights.sort((a, b) => a[2] - b[2]);
  225.  
  226. // earliest[i] = earliest known arrival at airport i
  227. const earliest = Array(airportCount).fill(Infinity);
  228.  
  229. earliest[startAirport] = 0;
  230.  
  231. for (const [origin, destination, departure, arrival] of flights) {
  232.  
  233. // Check if we can board this flight
  234. // and improve the destination's arrival time
  235. if (
  236. earliest[origin] <= departure &&
  237. arrival < earliest[destination]
  238. ) {
  239. earliest[destination] = arrival;
  240. }
  241. }
  242.  
  243. return earliest[targetAirport] !== Infinity;
  244. }
  245.  
  246.  
  247. // ==================== TEST CASES ====================
  248.  
  249. const tests = [
  250. {
  251. name: "Valid connection at equal time",
  252. airportCount: 3,
  253. flights: [
  254. [0, 1, 2, 5],
  255. [1, 2, 5, 8]
  256. ],
  257. startAirport: 0,
  258. targetAirport: 2,
  259. expected: true
  260. },
  261. {
  262. name: "Missed connecting flight",
  263. airportCount: 3,
  264. flights: [
  265. [0, 1, 2, 6],
  266. [1, 2, 5, 8]
  267. ],
  268. startAirport: 0,
  269. targetAirport: 2,
  270. expected: false
  271. },
  272. {
  273. name: "Multiple routes and unsorted flights",
  274. airportCount: 4,
  275. flights: [
  276. [1, 3, 8, 10],
  277. [0, 2, 1, 4],
  278. [2, 1, 5, 7],
  279. [0, 1, 9, 12]
  280. ],
  281. startAirport: 0,
  282. targetAirport: 3,
  283. expected: true
  284. },
  285. {
  286. name: "Earlier departure but later arrival",
  287. airportCount: 3,
  288. flights: [
  289. [0, 1, 1, 10],
  290. [0, 1, 2, 4],
  291. [1, 2, 5, 8]
  292. ],
  293. startAirport: 0,
  294. targetAirport: 2,
  295. expected: true
  296. },
  297. {
  298. name: "Start and target are the same",
  299. airportCount: 3,
  300. flights: [],
  301. startAirport: 0,
  302. targetAirport: 0,
  303. expected: true
  304. },
  305. {
  306. name: "No available flights",
  307. airportCount: 3,
  308. flights: [],
  309. startAirport: 0,
  310. targetAirport: 2,
  311. expected: false
  312. }
  313. ];
  314.  
  315.  
  316. // ==================== TEST RUNNER ====================
  317.  
  318. tests.forEach((test, index) => {
  319.  
  320. const actual = canReachDestination(
  321. test.airportCount,
  322. test.flights,
  323. test.startAirport,
  324. test.targetAirport
  325. );
  326.  
  327. console.log(`Test ${index + 1}: ${test.name}`);
  328. console.log("Expected:", test.expected);
  329. console.log("Actual: ", actual);
  330. console.log(
  331. actual === test.expected ? "PASS" : "FAIL"
  332. );
  333. console.log("------------------------------");
  334. });
Success #stdin #stdout 0.03s 5596KB
stdin
Standard input is empty
stdout
Test 1: Valid connection at equal time
Expected: true
Actual:   true
PASS
------------------------------
Test 2: Missed connecting flight
Expected: false
Actual:   false
PASS
------------------------------
Test 3: Multiple routes and unsorted flights
Expected: true
Actual:   true
PASS
------------------------------
Test 4: Earlier departure but later arrival
Expected: true
Actual:   true
PASS
------------------------------
Test 5: Start and target are the same
Expected: true
Actual:   true
PASS
------------------------------
Test 6: No available flights
Expected: false
Actual:   false
PASS
------------------------------