/332. Reconstruct Itinerary

332. Reconstruct Itinerary

Hard
Arrays44.3% acceptance

Given a list of directed edges representing connections between nodes, where each edge is a pair [source, destination], reconstruct a path starting from the node "JFK" that uses all edges exactly once. If multiple valid paths exist, return the one with the smallest lexicographical order. Each node name is a string of three uppercase English letters. All edges must be used exactly once, and at least one valid path exists.

Example 1

Input: [[JFK,AAA],[AAA,BBB],[BBB,CCC],[CCC,JFK]]

Output: [JFK,AAA,BBB,CCC,JFK]

Explanation: The only valid path uses all edges in order.

Example 2

Input: [[JFK,AAA],[JFK,BBB],[BBB,AAA],[AAA,JFK]]

Output: [JFK,AAA,JFK,BBB,AAA]

Explanation: Lexicographically smallest path is chosen.

Constraints

  • 1 <= len(edges) <= 300
  • len(edges[i]) == 2
  • len(edges[i][0]) == 3
  • len(edges[i][1]) == 3
  • edges[i][0] and edges[i][1] are uppercase English letters
  • edges[i][0] != edges[i][1]
  • All edges form at least one valid path starting from JFK
Python (current runtime)

Case 1

Input: [['JFK','XYZ'],['XYZ','DEF'],['DEF','JFK']]

Expected: ['JFK','XYZ','DEF','JFK']

Case 2

Input: [['JFK','AAA'],['AAA','JFK'],['JFK','BBB'],['BBB','AAA']]

Expected: ['JFK','AAA','JFK','BBB','AAA']

Case 3

Input: [['JFK','AAA'],['AAA','BBB'],['BBB','JFK'],['JFK','CCC'],['CCC','AAA']]

Expected: ['JFK','AAA','BBB','JFK','CCC','AAA']