Reconstruct Itinerary
Hard
Topics
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
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.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
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
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
- Group the tickets by departure airport and sort each group so the smallest destination is taken first.
- Walk from
JFK. At each airport, consume its smallest remaining ticket and move on. - 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.
- 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)import java.util.*;
class Solution {
public String findItinerary(String[] words) {
departures = new HashMap<>();
for (int i = 0; i + 1 < words.length; i += 2) {
departures.computeIfAbsent(words[i], x -> new ArrayList<>()).add(words[i + 1]);
}
for (List<String> list : departures.values()) {
list.sort(Comparator.reverseOrder());
}
route = new ArrayList<>();
visit("JFK");
Collections.reverse(route);
return String.join(" ", route);
}
private Map<String, List<String>> departures;
private List<String> route;
private void visit(String airport) {
List<String> list = departures.get(airport);
while (list != null && !list.isEmpty()) {
visit(list.remove(list.size() - 1));
}
route.add(airport);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string findItinerary(vector<string>& words) {
map<string, vector<string>> departures;
for (size_t i = 0; i + 1 < words.size(); i += 2) {
departures[words[i]].push_back(words[i + 1]);
}
for (auto& kv : departures) {
sort(kv.second.begin(), kv.second.end(), greater<string>());
}
vector<string> route;
function<void(const string&)> visit = [&](const string& airport) {
auto& list = departures[airport];
while (!list.empty()) {
string next = list.back();
list.pop_back();
visit(next);
}
route.push_back(airport);
};
visit("JFK");
reverse(route.begin(), route.end());
string out;
for (size_t i = 0; i < route.size(); i++) {
if (i) out += " ";
out += route[i];
}
return out;
}
};/**
* @param {string[]} words
* @return {string}
*/ var findItinerary = function(words) {
const departures = new Map();
for (let i = 0; i + 1 < words.length; i += 2) {
if (!departures.has(words[i])) departures.set(words[i], []);
departures.get(words[i]).push(words[i + 1]);
}
for (const list of departures.values()) list.sort().reverse();
const route = [];
const visit = (airport) => {
const list = departures.get(airport) || [];
while (list.length) visit(list.pop());
route.push(airport);
};
visit("JFK");
route.reverse();
return route.join(" ");
};