Reconstruct Itinerary

Hard

Topics
GraphDFSEulerian Circuit

You are given a list of one-way flight tickets. Reconstruct the itinerary that starts at JFK and uses every ticket exactly once.

Several such itineraries may exist. Return the one that is smallest when read as a single list of airports — so at the first airport where two itineraries differ, the one with the alphabetically smaller code wins. At least one valid itinerary is guaranteed.

Return the airports in order, separated by single spaces.

The judge passes one flat list of airport codes, which it calls words: each consecutive pair is one ticket, so ["JFK","ATL","ATL","SFO"] is the two tickets JFK→ATL and ATL→SFO. LeetCode passes a list of pairs.

Example 1

ticketsMUC → LHRJFK → MUCSFO → SJCLHR → SFO
itineraryJFKMUCLHRSFOSJC
one ticket, used exactly onceairports in visiting order
Every ticket above has to be used exactly once, and the trip always begins at JFK. Where more than one unused ticket leaves the airport you are standing at, the one whose destination comes first alphabetically is taken, which is what makes a single answer well defined. The lower row is the resulting airport sequence, and it has 5 entries for 4 tickets because the starting airport is listed too.
The same pair of airports can appear as more than one ticket; each copy still has to be flown.
Input:  words = ["MUC","LHR","JFK","MUC","SFO","SJC","LHR","SFO"]
Output: "JFK MUC LHR SFO SJC"
Explanation: The four tickets are MUC→LHR, JFK→MUC, SFO→SJC and LHR→SFO. Only one order uses them all from JFK.

Example 2

ticketsJFK → SFOJFK → ATLSFO → ATLATL → JFKATL → SFO
itineraryJFKATLJFKSFOATLSFO
one ticket, used exactly onceairports in visiting order
Input:  words = ["JFK","SFO","JFK","ATL","SFO","ATL","ATL","JFK","ATL","SFO"]
Output: "JFK ATL JFK SFO ATL SFO"
Explanation: Starting with ATL rather than SFO is alphabetically smaller, and it still manages to use every ticket.

Example 3

ticketsJFK → ATLATL → SFO
itineraryJFKATLSFO
one ticket, used exactly onceairports in visiting order
Input:  words = ["JFK","ATL","ATL","SFO"]
Output: "JFK ATL SFO"
Explanation: A single chain with no choices to make.

Constraints

  • 1 <= number of tickets <= 300
  • Each airport code is three uppercase letters
  • At least one valid itinerary exists
Editorial — intuition, approach, complexity and pitfalls

Intuition

The itinerary uses every ticket exactly once, which makes this a trail through all the edges of a directed graph rather than a path between two vertices. That distinction matters: there is no notion of a "shortest" route here, only of a complete one.

The greedy instinct — always fly to the alphabetically smallest reachable airport — is almost right and fails on example 2. From JFK the smaller option is ATL, and that is correct; but a greedy walk can strand itself at an airport with unused tickets elsewhere, because it spends a ticket it needed later. The walk has to be able to recover.

The recovery is what makes the standard construction elegant: walk forward taking the smallest unused ticket each time, and when you run out of tickets at an airport, prepend that airport to the answer and step back. An airport you get stuck at must be the end of the itinerary, and an airport you get stuck at a second time must come just before it. Building the answer backwards this way turns the dead end from a failure into information.

The alphabetical tie-break then falls out of visiting each airport’s destinations in sorted order, because the forward walk commits to the smallest choice it can and only unwinds when there is nothing left.

Approach

  1. Group the tickets by departure airport and sort each group so the smallest destination is taken first.
  2. Walk from JFK. At each airport, consume its smallest remaining ticket and move on.
  3. When an airport has no tickets left, add it to the front of the result and return to the airport you came from, which then tries its next ticket.
  4. When the walk unwinds completely, the result holds every airport in order and its length is the ticket count plus one.

Walkthrough

tickets: JFK->SFO, JFK->ATL, SFO->ATL, ATL->JFK, ATL->SFO

destinations, sorted
   JFK: ATL, SFO
   ATL: JFK, SFO
   SFO: ATL

walk forward, always the smallest unused
   JFK -> ATL -> JFK -> SFO -> ATL -> SFO
   at SFO nothing is left

unwind, prepending each stuck airport
   SFO                      -> [SFO]
   ATL has nothing left     -> [ATL, SFO]
   SFO has nothing left     -> [SFO, ATL, SFO]
   JFK has nothing left     -> [JFK, SFO, ATL, SFO]
   ATL has nothing left     -> [ATL, JFK, SFO, ATL, SFO]
   JFK has nothing left     -> [JFK, ATL, JFK, SFO, ATL, SFO]

answer JFK ATL JFK SFO ATL SFO

The forward walk never had to guess: it always took the
smaller airport, and the prepending turned each dead end into
the next position from the back.

Complexity

  • Time — O(m log m): each ticket is consumed once; the log factor is sorting the destination lists.
  • Space — O(m): the grouped tickets, the route, and a recursion as deep as the itinerary.

Common Pitfalls

  • Appending airports as you go rather than prepending as you unwind. The forward order is wrong precisely on the inputs where the walk gets stuck, which is example 2.
  • Giving up when an airport has no tickets left. That is not a failure, it is the signal that the airport belongs at the end of what remains.
  • Sorting the destinations ascending and then taking from the end. Taking the smallest first is what delivers the tie-break, so either sort descending and pop, or sort ascending and take from the front.
  • Marking airports visited. Airports are revisited freely — example 2 passes through JFK twice. It is tickets that are used up, not airports.
  • Starting anywhere other than JFK.

Full Solution — all languages

class Solution:
    def findItinerary(self, words):
        departures = {}
        for i in range(0, len(words) - 1, 2):
            departures.setdefault(words[i], []).append(words[i + 1])
        for airport in departures:
            departures[airport].sort(reverse=True)

        route = []

        def visit(airport):
            while departures.get(airport):
                visit(departures[airport].pop())
            route.append(airport)

        visit("JFK")
        route.reverse()
        return " ".join(route)
SensAI
Beta
Tap the mic to stop voice mode