Skip to content
Decoder

Reconstruct Itinerary

Hard

Problem

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.

Example 1

tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]

Example 2

  →  ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 3

tickets = [["JFK", "KUL"], ["JFK", "NRT"], ["NRT", "JFK"]]

Example 4

  →  ["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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.