15% off all plans & roadmaps Use code
See plansReconstruct Itinerary
- LeetCode 332
- Hard
- Stack Patterns
- Simulation / Backtracking Helper
Updated
TL;DR: Use every flight ticket exactly once, starting at JFK, and return the lexicographically smallest route. Hierholzer's algorithm with a stack and sorted destinations finds it in O(E log E).
Problem
You get a list of airline tickets, where tickets[i] = [from, to] is one directed flight from airport from to airport to. An itinerary is a sequence of airports in which each consecutive pair matches a ticket.
Build an itinerary that starts at "JFK" and uses every ticket exactly once. Duplicate tickets are separate flights, so each copy must be used on its own.
A valid itinerary is guaranteed to exist. If several valid itineraries exist, return the one that is smallest in lexicographical order when you compare the airport sequences from left to right.
Example 1
Input: tickets = [["JFK","BOS"],["BOS","DEN"],["DEN","JFK"],["JFK","LIM"],["LIM","BOS"]] Output: ["JFK","BOS","DEN","JFK","LIM","BOS"] Explanation: From JFK you take the BOS ticket before the LIM ticket to get the smallest second airport. The route then goes BOS to DEN, DEN to JFK, JFK to LIM, and LIM to BOS, which uses all five tickets.
Example 2
Input: tickets = [["JFK","AMS"],["JFK","BER"],["AMS","BER"],["BER","JFK"]] Output: ["JFK","AMS","BER","JFK","BER"] Explanation: AMS is smaller than BER, so the route starts JFK to AMS. The remaining tickets then force AMS to BER, BER to JFK, and JFK to BER.
Example 3
Input: tickets = [["JFK","OSL"],["OSL","JFK"],["JFK","RIX"],["RIX","JFK"],["JFK","OSL"]] Output: ["JFK","OSL","JFK","RIX","JFK","OSL"] Explanation: The route takes JFK to OSL and back to JFK. Taking the second JFK to OSL ticket at that point would strand you at OSL with tickets left, so the route must go to RIX first and finish with the last JFK to OSL ticket.
Constraints
1 <= tickets.length <= 300tickets[i].length == 2- Every airport code is exactly 3 uppercase English letters.
- The itinerary must start at
"JFK". - At least one valid itinerary uses every ticket exactly once.
Constraints that matter
- tickets.length is at most 300, so an O(E log E) graph solution is trivial, but trying every ticket order (up to 300 factorial) is hopeless in the worst case.
- A valid itinerary is guaranteed, so you never need to detect failure. This is what lets Hierholzer's algorithm skip any feasibility check.
- Duplicate tickets are allowed, so you must store destinations in a multiset (a heap or a sorted list), never a set.
- Airport codes are fixed-length uppercase strings, so plain string comparison gives the required lexicographic order in every language.
- The route has E + 1 airports and recursion can reach depth E, which is 300 here. That is safe in Python, but an explicit stack removes the worry.
Hints
Hint 1
Each ticket is a directed edge, and you must use every edge exactly once.
Hint 2
Sort the tickets so that, for each airport, destinations come in alphabetical order.
Solution
Intuition
Each ticket is a directed edge, and you must use every edge exactly once. That is an Eulerian path problem. The route is a walk that crosses every edge one time, starting at JFK.
Picture a hiker walking trails and writing a junction in the notebook only after every trail leaving it is used up. The stack is the hiker's current path, and the notebook is the route list, so reversing the notebook gives the walk.
The lexicographic rule tempts you to be greedy: always take the smallest destination. Example 3 shows why that fails. From JFK the smallest ticket leads to OSL, then back to JFK, and a second OSL ticket leads to a dead end because OSL has no outgoing tickets left. The greedy walk gets stuck with the RIX tickets unused.
The fix is to notice that the dead-end airport must be the last stop of the route. So you still walk greedily, but you only write an airport into the answer when it has no outgoing tickets left. Dead ends get written first, and the cycles you skipped are spliced in before them as the stack unwinds. Reverse the written order and you have the itinerary.
This is a stack pattern. The explicit stack holds the current partial walk. When the top airport has an unused ticket, you push its smallest destination. When it has none, you pop it into the answer.
Because you always try the smallest destination first, the first complete walk this process finishes is the smallest one.
Worked example
Input: tickets = [["JFK","JFK"]] Output: ["JFK","JFK"] Explanation: There is one ticket, a flight from JFK back to JFK. The route starts at JFK, takes that ticket, and lands at JFK again, so the answer has two airports: one more than the number of tickets.

Solution pattern
Simulation / Backtracking Helper
Part of Stack Patterns
Approach 1: Brute force: sorted backtrackingSimulation / Backtracking Helper
Sort the tickets so that, for each airport, destinations come in alphabetical order. Then run a depth-first search over ticket choices. At each airport, try each unused ticket in sorted order, mark it used, recurse, and undo the mark if the branch fails.
Because tickets are tried in sorted order, the first complete itinerary the search finds is the lexicographically smallest. You can stop at the first success. To avoid repeating identical work, skip a ticket that equals the previous ticket when that previous copy is unused, since trying it would repeat the same branch.
Steps
- Copy the tickets and sort them by departure, then by destination.
- Create a
usedarray of E booleans and apathlist that starts withJFK. - Define
dfs: ifpathhas E + 1 airports, return true. - Scan all tickets. Skip a ticket if it is used, departs from a different airport than the last path airport, or duplicates the previous unused ticket.
- Mark the ticket used, append its destination, and call
dfs. If it returns true, return true. - Otherwise remove the destination and unmark the ticket, then try the next ticket.
- Return false when no ticket works, and return
pathafter the top-level call.
Dry run
Take [["JFK","JFK"]]. After sorting, there is one ticket. path = [JFK] and used = [false].
dfs sees path length 1, which is not E + 1 = 2. It scans ticket 0: unused and departs from JFK, which matches the last path airport. It marks the ticket used and appends JFK, so path = [JFK, JFK].
The recursive call sees path length 2 = E + 1 and returns true. The top call returns true and the answer is [JFK, JFK].
Complexity
| Time | O(E!) in the worst case |
|---|---|
| Space | O(E) |
Let E be the number of tickets. Each recursion level scans all E tickets, and in the worst case the search can try every ordering of the tickets, so the number of explored orders is bounded by E factorial. Real inputs prune hard, but dead ends deep in the search can still force heavy backtracking. Space is O(E) for the used array, the path, and a recursion depth of at most E.
PythonTested in our runner
from typing import List, Optional
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
ts = sorted(tickets)
n = len(ts)
used = [False] * n
path = ["JFK"]
def dfs() -> bool:
if len(path) == n + 1:
return True
cur = path[-1]
for i in range(n):
if used[i] or ts[i][0] != cur:
continue
# same flight as the previous copy, which was already tried
if i > 0 and ts[i] == ts[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(ts[i][1])
if dfs():
return True
path.pop()
used[i] = False
return False
dfs()
return path
JavaTested in our runner
import java.util.*;
class Solution {
private String[][] ts;
private boolean[] used;
private List<String> path;
public String[] findItinerary(String[][] tickets) {
ts = tickets.clone();
Arrays.sort(ts, (a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));
used = new boolean[ts.length];
path = new ArrayList<>();
path.add("JFK");
dfs();
return path.toArray(new String[0]);
}
private boolean dfs() {
if (path.size() == ts.length + 1) return true;
String cur = path.get(path.size() - 1);
for (int i = 0; i < ts.length; i++) {
if (used[i] || !ts[i][0].equals(cur)) continue;
if (i > 0 && !used[i - 1] && ts[i][0].equals(ts[i - 1][0]) && ts[i][1].equals(ts[i - 1][1])) continue;
used[i] = true;
path.add(ts[i][1]);
if (dfs()) return true;
path.remove(path.size() - 1);
used[i] = false;
}
return false;
}
}
C++Tested in our runner
using namespace std;
class Solution {
vector<vector<string>> ts;
vector<bool> used;
vector<string> path;
bool dfs() {
int n = ts.size();
if ((int)path.size() == n + 1) return true;
string cur = path.back();
for (int i = 0; i < n; i++) {
if (used[i] || ts[i][0] != cur) continue;
if (i > 0 && !used[i - 1] && ts[i] == ts[i - 1]) continue;
used[i] = true;
path.push_back(ts[i][1]);
if (dfs()) return true;
path.pop_back();
used[i] = false;
}
return false;
}
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
ts = tickets;
sort(ts.begin(), ts.end());
used.assign(ts.size(), false);
path.clear();
path.push_back("JFK");
dfs();
return path;
}
};
JavaScriptTested in our runner
/**
* @param {string[][]} tickets
* @return {string[]}
*/
var findItinerary = function(tickets) {
const ts = tickets.map(t => [t[0], t[1]]);
ts.sort((a, b) => {
if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1;
if (a[1] !== b[1]) return a[1] < b[1] ? -1 : 1;
return 0;
});
const n = ts.length;
const used = new Array(n).fill(false);
const path = ["JFK"];
const dfs = () => {
if (path.length === n + 1) return true;
const cur = path[path.length - 1];
for (let i = 0; i < n; i++) {
if (used[i] || ts[i][0] !== cur) continue;
if (i > 0 && !used[i - 1] && ts[i][0] === ts[i - 1][0] && ts[i][1] === ts[i - 1][1]) continue;
used[i] = true;
path.push(ts[i][1]);
if (dfs()) return true;
path.pop();
used[i] = false;
}
return false;
};
dfs();
return path;
};
GoTested in our runner
import "sort"
func findItinerary(tickets [][]string) []string {
ts := make([][]string, len(tickets))
copy(ts, tickets)
sort.Slice(ts, func(i, j int) bool {
if ts[i][0] != ts[j][0] {
return ts[i][0] < ts[j][0]
}
return ts[i][1] < ts[j][1]
})
n := len(ts)
used := make([]bool, n)
path := []string{"JFK"}
var dfs func() bool
dfs = func() bool {
if len(path) == n+1 {
return true
}
cur := path[len(path)-1]
for i := 0; i < n; i++ {
if used[i] || ts[i][0] != cur {
continue
}
if i > 0 && !used[i-1] && ts[i][0] == ts[i-1][0] && ts[i][1] == ts[i-1][1] {
continue
}
used[i] = true
path = append(path, ts[i][1])
if dfs() {
return true
}
path = path[:len(path)-1]
used[i] = false
}
return false
}
dfs()
return path
}
C#Tested in our runner
public class Solution {
public string[] findItinerary(string[][] tickets) {
var ts = tickets
.OrderBy(t => t[0], StringComparer.Ordinal)
.ThenBy(t => t[1], StringComparer.Ordinal)
.ToArray();
int n = ts.Length;
var used = new bool[n];
var path = new List<string> { "JFK" };
bool Dfs() {
if (path.Count == n + 1) return true;
string cur = path[path.Count - 1];
for (int i = 0; i < n; i++) {
if (used[i] || ts[i][0] != cur) continue;
if (i > 0 && !used[i - 1] && ts[i][0] == ts[i - 1][0] && ts[i][1] == ts[i - 1][1]) continue;
used[i] = true;
path.Add(ts[i][1]);
if (Dfs()) return true;
path.RemoveAt(path.Count - 1);
used[i] = false;
}
return false;
}
Dfs();
return path.ToArray();
}
}
Approach 2: Hierholzer's algorithm with a stackOptimal
What's slow: backtracking guesses a ticket, walks far down the branch, discovers a dead end, and undoes work. The same suffixes get rebuilt again and again, and the scan over all E tickets at each step adds more cost.
The insight that fixes it: a dead-end airport can only be the end of the route, so you never need to undo it. Walk greedily with the smallest destination, and write an airport into the answer only when it has no unused tickets. The airports come out in reverse order, so reverse them at the end. Each ticket is consumed once and never put back.
Store each airport's destinations so the smallest one is cheap to remove: a min-heap, or a list sorted in descending order so that pop() from the end gives the smallest. Use an explicit stack so recursion depth is never a concern.
Why it is correct. The first airport the walk gets stuck at must be the final stop, since nothing leaves it. Every other airport is written only after all its departures are used, so each detour is spliced in before the point where it branched off. Reversing the written order therefore uses every ticket once, and taking the smallest destination first keeps the result lexicographically smallest.
Steps
- Build a map from each departure airport to its destinations, kept so the smallest is removed first (a min-heap or a descending sorted list).
- Push
JFKonto the stack and create an emptyroutelist. - While the stack is not empty, look at the top airport.
- If the top airport has an unused ticket, remove its smallest destination and push it onto the stack.
- Otherwise, pop the top airport and append it to
route. - When the stack is empty, reverse
routeand return it.
Dry run
| Step | Stack (top on right) | Tickets left at JFK | Action | route |
|---|---|---|---|---|
| 0 | [JFK] | [JFK] | start | [] |
| 1 | [JFK, JFK] | [] | top JFK has a ticket, remove JFK and push it | [] |
| 2 | [JFK] | [] | top JFK has no tickets, pop and record | [JFK] |
| 3 | [] | [] | top JFK has no tickets, pop and record | [JFK, JFK] |
The stack is empty, so reverse route = [JFK, JFK]. Both entries are the same, so the reversed list is [JFK, JFK], which matches the expected output.
A second check on Example 3 shows the dead end. The walk goes JFK, OSL, JFK, OSL, and the last OSL has no tickets, so OSL is recorded first. Popping back to JFK finds the RIX ticket, which pushes RIX and JFK. After those pop, the route is recorded as OSL, JFK, RIX, JFK, OSL, JFK, and reversing it gives the expected answer.
Complexity
| Time | O(E log E) |
|---|---|
| Space | O(E) |
Let E be the number of tickets. Building the structure costs O(E log E) for heap inserts or sorting. Each ticket is removed exactly once, and each removal costs at most O(log E) with a heap. The loop runs 2E + 1 iterations in total: one push per ticket plus one pop per stack entry. Space is O(E) because the map holds E destinations, and the stack and route each hold at most E + 1 airports.
PythonTested in our runner
from typing import List, Optional
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
graph = {}
# descending order, so pop() from the end gives the smallest destination
for src, dst in sorted(tickets, reverse=True):
graph.setdefault(src, []).append(dst)
stack = ["JFK"]
route = []
while stack:
top = stack[-1]
if graph.get(top):
stack.append(graph[top].pop())
else:
route.append(stack.pop())
return route[::-1]
JavaTested in our runner
import java.util.*;
class Solution {
public String[] findItinerary(String[][] tickets) {
Map<String, PriorityQueue<String>> graph = new HashMap<>();
for (String[] t : tickets) {
graph.computeIfAbsent(t[0], k -> new PriorityQueue<>()).add(t[1]);
}
Deque<String> stack = new ArrayDeque<>();
List<String> route = new ArrayList<>();
stack.push("JFK");
while (!stack.isEmpty()) {
String top = stack.peek();
PriorityQueue<String> q = graph.get(top);
if (q != null && !q.isEmpty()) {
stack.push(q.poll());
} else {
route.add(stack.pop());
}
}
Collections.reverse(route);
return route.toArray(new String[0]);
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string, priority_queue<string, vector<string>, greater<string>>> graph;
for (auto& t : tickets) {
graph[t[0]].push(t[1]);
}
vector<string> stack{"JFK"};
vector<string> route;
while (!stack.empty()) {
string top = stack.back();
auto it = graph.find(top);
if (it != graph.end() && !it->second.empty()) {
stack.push_back(it->second.top());
it->second.pop();
} else {
route.push_back(top);
stack.pop_back();
}
}
reverse(route.begin(), route.end());
return route;
}
};
JavaScriptTested in our runner
/**
* @param {string[][]} tickets
* @return {string[]}
*/
var findItinerary = function(tickets) {
const graph = new Map();
for (const [src, dst] of tickets) {
if (!graph.has(src)) graph.set(src, []);
graph.get(src).push(dst);
}
// descending order, so pop() from the end gives the smallest destination
for (const list of graph.values()) {
list.sort((x, y) => (x < y ? 1 : x > y ? -1 : 0));
}
const stack = ["JFK"];
const route = [];
while (stack.length > 0) {
const top = stack[stack.length - 1];
const list = graph.get(top);
if (list && list.length > 0) {
stack.push(list.pop());
} else {
route.push(stack.pop());
}
}
return route.reverse();
};
GoTested in our runner
import "sort"
func findItinerary(tickets [][]string) []string {
graph := map[string][]string{}
for _, t := range tickets {
graph[t[0]] = append(graph[t[0]], t[1])
}
// descending order, so the last element is the smallest destination
for k := range graph {
sort.Sort(sort.Reverse(sort.StringSlice(graph[k])))
}
stack := []string{"JFK"}
route := []string{}
for len(stack) > 0 {
top := stack[len(stack)-1]
list := graph[top]
if len(list) > 0 {
stack = append(stack, list[len(list)-1])
graph[top] = list[:len(list)-1]
} else {
route = append(route, top)
stack = stack[:len(stack)-1]
}
}
for i, j := 0, len(route)-1; i < j; i, j = i+1, j-1 {
route[i], route[j] = route[j], route[i]
}
return route
}
C#Tested in our runner
public class Solution {
public string[] findItinerary(string[][] tickets) {
var graph = new Dictionary<string, List<string>>();
foreach (var t in tickets) {
if (!graph.ContainsKey(t[0])) graph[t[0]] = new List<string>();
graph[t[0]].Add(t[1]);
}
// descending order, so the last element is the smallest destination
foreach (var list in graph.Values) {
list.Sort((a, b) => string.CompareOrdinal(b, a));
}
var stack = new List<string> { "JFK" };
var route = new List<string>();
while (stack.Count > 0) {
string top = stack[stack.Count - 1];
if (graph.TryGetValue(top, out var list) && list.Count > 0) {
stack.Add(list[list.Count - 1]);
list.RemoveAt(list.Count - 1);
} else {
route.Add(top);
stack.RemoveAt(stack.Count - 1);
}
}
route.Reverse();
return route.ToArray();
}
}
Common mistakes
- Using a plain greedy walk,
route.append(next)as soon as you pick the smallest destination. Example 3 breaks it because the walk dead-ends at OSL. Record an airport only when it has no tickets left, then reverse. - Storing destinations in a
set. Duplicate tickets such as two JFK to OSL flights collapse into one, so the route comes up short. Use a heap, a list, or a multiset. - Forgetting the final
reverse. The stack pops airports from the end of the trip to the start, so returningrouteas is gives the itinerary backward. - Popping the largest destination from a list sorted in ascending order. If you pop from the end, sort descending. If you pop from the front, sort ascending and accept an O(n) removal, or use a heap.
- In the backtracking version, not restoring state on failure:
used[i] = truewithoutused[i] = false, orpath.appendwithoutpath.pop. Later branches then see tickets as spent and the search returns a wrong or empty path. - Returning the first complete walk from unsorted tickets in backtracking. The first success is only the smallest if you try tickets in sorted order, so sort first.
Edge cases
- One ticket
[["JFK","JFK"]]returns["JFK","JFK"], a self-loop used once. - A single ticket
[["JFK","ABC"]]returns["JFK","ABC"]. - Duplicate tickets such as two
JFKtoOSLflights must both be used, soOSLappears twice in the route. - A dead-end airport reachable from JFK, as in Example 3, must be visited last even though it is alphabetically small.
- A long chain of 300 tickets such as JFK to AAA to BBB and so on produces a 301-airport route. An explicit stack handles it with no recursion limit.
- An airport that never departs (no entry in the map) must not crash the lookup. Use
getwith a default or check for a missing key.
Follow-ups interviewers ask
- Why does reversing the postorder give the right route?
- An airport is recorded only when it has no tickets left, so the first airport recorded is the end of the whole trip. Each later record is the airport that precedes it in some valid ordering of the edges. Reading the records backward therefore gives the walk from start to finish. Taking the smallest destination first means the earliest choices in that walk are the smallest possible.
- What changes if no valid itinerary is guaranteed?
- Check feasibility first. After the algorithm, verify that the route has E + 1 airports and starts at the required start. If it is shorter, some tickets were unreachable and no Eulerian path exists. You can also check degree conditions up front: at most one airport with out minus in equal to 1, one with in minus out equal to 1, and all others balanced.
- Can you do it recursively, and what is the risk?
- Yes. Define
visit(airport)to pop smallest destinations and recurse until none remain, then append the airport, and reverse at the end. The depth is at most E, which is 300 here, so it fits in default limits. For much larger inputs, the explicit stack avoids a stack overflow.
Reconstruct Itinerary FAQ
What is the time complexity of Reconstruct Itinerary?
The stack-based Hierholzer solution runs in O(E log E), where E is the number of tickets. Sorting or heap inserts cost O(E log E), and each ticket is removed once. The sorted backtracking approach is exponential in the worst case.
Why use Hierholzer's algorithm for Reconstruct Itinerary?
The tickets form a directed graph and you need a path that uses every edge exactly once, which is an Eulerian path. Hierholzer's algorithm builds one in linear steps by recording airports when they run out of tickets. It handles dead ends and cycles without backtracking.
Why does the greedy smallest-first walk fail without postorder recording?
Taking the smallest destination can lead into an airport with no outgoing tickets while other tickets remain, as in Example 3. Writing airports to the answer as you visit them would lock in that bad ordering. Recording them on exit lets the dead end sit at the end and splices the other tickets in before it.
Can Reconstruct Itinerary be solved in O(1) extra space?
No. You need to remember which tickets are unused, and that takes O(E) space. The route itself has E + 1 airports, so the output alone is that large.
How do I write Reconstruct Itinerary in Python or Java?
In Python, sort the tickets in reverse, append each destination to a list per source, and pop from the end while using a list as the stack. In Java, use a HashMap of PriorityQueue<String> and an ArrayDeque as the stack. Both versions are above and follow the same steps.
Is LeetCode 332 solvable with plain backtracking?
Yes, with sorted tickets and a used array, and it returns the correct answer on valid inputs. The worst case is exponential, so Hierholzer is the safe choice for an interview. Mention the backtracking first, then explain why you replace it.
Asked at
See which companies ask this — Pro
Related problems
- Simplify Path · same technique: Simulation / Backtracking Helper
- Decode String · same technique: Simulation / Backtracking Helper
- Asteroid Collision · same technique: Simulation / Backtracking Helper
- Baseball Game · same technique: Simulation / Backtracking Helper
- Crawler Log Folder · same technique: Simulation / Backtracking Helper
- Largest Rectangle in Histogram · same pattern: Stack Patterns
- Maximum Frequency Stack · same pattern: Stack Patterns
- Basic Calculator · same pattern: Stack Patterns
- Longest Valid Parentheses · same pattern: Stack Patterns
- Maximal Rectangle · same pattern: Stack Patterns