fork download
  1. /*
  2. PROBLEM:
  3. Reach a Destination Through Scheduled Flights
  4.  
  5. Determine whether we can reach targetAirport from
  6. startAirport through a valid sequence of flights.
  7.  
  8.  
  9. APPROACH: Optimized BFS + Adjacency List + Sorting
  10.  
  11. 1. Construct an adjacency list for every airport.
  12.  
  13. 2. Sort outgoing flights of each airport by
  14.   departure time in descending order.
  15.  
  16. 3. Maintain earliest[i], representing the earliest
  17.   known arrival time at airport i.
  18.  
  19. 4. Maintain pointer[i], representing the next
  20.   unprocessed outgoing flight of airport i.
  21.  
  22. 5. Initialize earliest[startAirport] = 0
  23.   and enqueue startAirport.
  24.  
  25. 6. For every airport dequeued:
  26.  
  27.   - Check its outgoing flights starting from
  28.   pointer[curr].
  29.  
  30.   - If the flight's departure time is smaller
  31.   than earliest[curr], stop processing.
  32.  
  33.   - Otherwise, advance the pointer.
  34.  
  35.   - If the flight improves the earliest arrival
  36.   at its destination, update it and enqueue
  37.   the destination.
  38.  
  39. 7. Return whether the target airport is reachable.
  40.  
  41.  
  42. WHY SORT IN DESCENDING ORDER?
  43.  
  44. When an airport is reached again with an earlier
  45. arrival time, additional flights may become available.
  46.  
  47. By sorting in descending order and maintaining a
  48. pointer, we can resume from the first unprocessed
  49. flight instead of scanning all outgoing flights again.
  50.  
  51. Each flight needs to be successfully processed
  52. at most once.
  53.  
  54.  
  55. TIME COMPLEXITY: O(V + E log E)
  56.  
  57. V = Number of airports
  58. E = Number of flights
  59.  
  60. - Construct adjacency list: O(V + E)
  61. - Sort outgoing flights: O(E log E) worst case
  62. - Initialize earliest and pointer arrays: O(V)
  63. - BFS traversal: O(V + E)
  64.  
  65. Each flight is processed at most once successfully.
  66. Each successful earliest-arrival update causes
  67. at most one enqueue.
  68.  
  69. Each dequeue can additionally perform at most
  70. one unsuccessful departure-time check.
  71.  
  72. Total: O(V + E log E)
  73.  
  74.  
  75. SPACE COMPLEXITY: O(V + E)
  76.  
  77. - Adjacency list: O(V + E)
  78. - Earliest arrival array: O(V)
  79. - Pointer array: O(V)
  80. - BFS queue: O(E)
  81. - Sorting auxiliary space: O(E) worst case
  82.  
  83. Total: O(V + E)
  84. */
  85.  
  86.  
  87. // ==================== SOLUTION ====================
  88.  
  89. function canReachDestination(
  90. airportCount, flights, startAirport, targetAirport
  91. ) {
  92. if (startAirport === targetAirport) return true;
  93.  
  94. // Step 1: Construct adjacency list
  95. const adj = Array.from(
  96. { length: airportCount }, () => []
  97. );
  98.  
  99. for (const [origin, destination, departure, arrival] of flights) {
  100. adj[origin].push([destination, departure, arrival]);
  101. }
  102.  
  103. // Step 2: Sort outgoing flights by descending departure
  104. for (const outgoing of adj) {
  105. outgoing.sort((a, b) => b[1] - a[1]);
  106. }
  107.  
  108. // Step 3: Earliest arrival at every airport
  109. const earliest = Array(airportCount).fill(Infinity);
  110. earliest[startAirport] = 0;
  111.  
  112. // Step 4: Next unprocessed flight for every airport
  113. const pointer = Array(airportCount).fill(0);
  114.  
  115. const q = [startAirport];
  116. let head = 0;
  117.  
  118. // Step 5: BFS
  119. while (head < q.length) {
  120.  
  121. const curr = q[head++];
  122.  
  123. if (curr === targetAirport) return true;
  124.  
  125. const outgoing = adj[curr];
  126.  
  127. while (pointer[curr] < outgoing.length) {
  128.  
  129. const [next, departure, arrival] =
  130. outgoing[pointer[curr]];
  131.  
  132. // Cannot board this flight yet
  133. if (departure < earliest[curr]) {
  134. break;
  135. }
  136.  
  137. // Mark this flight as processed
  138. pointer[curr]++;
  139.  
  140. // Check if this flight improves arrival time
  141. if (arrival < earliest[next]) {
  142. earliest[next] = arrival;
  143. q.push(next);
  144. }
  145. }
  146. }
  147.  
  148. return false;
  149. }
  150.  
  151.  
  152. // ==================== TEST CASES ====================
  153.  
  154. const tests = [
  155. {
  156. name: "Valid connection at equal time",
  157. airportCount: 3,
  158. flights: [
  159. [0, 1, 2, 5],
  160. [1, 2, 5, 8]
  161. ],
  162. startAirport: 0,
  163. targetAirport: 2,
  164. expected: true
  165. },
  166. {
  167. name: "Missed connecting flight",
  168. airportCount: 3,
  169. flights: [
  170. [0, 1, 2, 6],
  171. [1, 2, 5, 8]
  172. ],
  173. startAirport: 0,
  174. targetAirport: 2,
  175. expected: false
  176. },
  177. {
  178. name: "Revisit airport with earlier arrival",
  179. airportCount: 5,
  180. flights: [
  181. [0, 1, 9, 12],
  182. [0, 2, 1, 4],
  183. [2, 1, 5, 7],
  184. [1, 3, 8, 10],
  185. [1, 4, 13, 15]
  186. ],
  187. startAirport: 0,
  188. targetAirport: 3,
  189. expected: true
  190. },
  191. {
  192. name: "Start and target are the same",
  193. airportCount: 3,
  194. flights: [],
  195. startAirport: 0,
  196. targetAirport: 0,
  197. expected: true
  198. }
  199. ];
  200.  
  201.  
  202. // ==================== TEST RUNNER ====================
  203.  
  204. tests.forEach((test, index) => {
  205.  
  206. const actual = canReachDestination(
  207. test.airportCount,
  208. test.flights,
  209. test.startAirport,
  210. test.targetAirport
  211. );
  212.  
  213. console.log(`Test ${index + 1}: ${test.name}`);
  214. console.log("Expected:", test.expected);
  215. console.log("Actual: ", actual);
  216. console.log(actual === test.expected ? "PASS" : "FAIL");
  217. console.log("------------------------------");
  218. });
Success #stdin #stdout 0.04s 5680KB
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: Revisit airport with earlier arrival
Expected: true
Actual:   true
PASS
------------------------------
Test 4: Start and target are the same
Expected: true
Actual:   true
PASS
------------------------------