Skip to content

Reconstruct Itinerary

HardGraphs
Decode it first. Clues, constraints, pattern and plan before any code.

You get a pile of plane tickets, each [from, to], all belonging to one traveller who started at "JFK". Rebuild the trip: return the list of airports in the order visited, using every ticket exactly once. If several trips are possible, return the one that is smallest in lexical order when read as a single list. At least one valid trip always exists.

tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
  →  ["JFK", "MUC", "LHR", "SFO", "SJC"]
 
tickets = [["JFK", "KUL"], ["JFK", "NRT"], ["NRT", "JFK"]]
  →  ["JFK", "NRT", "JFK", "KUL"]   ("KUL" is smaller, but going there first strands the other tickets)

Constraints

  • 1 <= tickets.length <= 300
  • Airport codes are 3 uppercase letters
  • A valid itinerary using all tickets always exists