Algo-Sim › Advanced Graphs
Reconstruct Itinerary
Hard · Advanced Graphs · step through it in Java, Python and C++ on your own input
Use every ticket exactly once, starting from JFK: Hierholzer’s algorithm for an Eulerian path, taking the smallest destination first.
Problem
Given airline tickets where tickets[i] = [from, to], reconstruct the itinerary in order. It must start at "JFK" and use every ticket exactly once. If several itineraries work, return the one that is smallest in lexical order when read as a single string.
Constraints
- 1 ≤ tickets.length ≤ 300
- Airport codes are 3 uppercase letters
- At least one valid itinerary exists
Edge cases to test
- A dead-end branch that must be visited last
- Duplicate tickets between the same airports
- One ticket
Follow-up questions
- Why does Hierholzer’s algorithm add airports in post-order?
- A dead end can only be the end of the trip; adding it when stuck and reversing at the end puts it last.
- What is the cost?
- O(E log E) for sorting the destinations, then O(E) for the walk.
Solution
Java
public List<String> findItinerary(List<List<String>> tickets) {
Map<String, PriorityQueue<String>> graph = new HashMap<>();
for (List<String> t : tickets) {
graph.computeIfAbsent(t.get(0), k -> new PriorityQueue<>()).add(t.get(1));
}
LinkedList<String> route = new LinkedList<>();
Deque<String> stack = new ArrayDeque<>();
stack.push("JFK");
while (!stack.isEmpty()) {
PriorityQueue<String> next = graph.get(stack.peek());
if (next != null && !next.isEmpty()) {
stack.push(next.poll());
} else {
route.addFirst(stack.pop());
}
}
return route;
}Python
from collections import defaultdict
def find_itinerary(tickets):
graph = defaultdict(list)
# Sorted backwards, so pop() hands out the smallest destination first.
for src, dst in sorted(tickets, reverse=True):
graph[src].append(dst)
stack, route = ["JFK"], []
while stack:
if graph[stack[-1]]:
stack.append(graph[stack[-1]].pop())
else:
route.append(stack.pop())
return route[::-1]C++
#include <bits/stdc++.h>
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 (vector<string> &t : tickets) {
graph[t[0]].push(t[1]);
}
deque<string> route = {};
deque<string> stack = {};
stack.push_back("JFK");
while (!stack.empty()) {
auto &next = graph[stack.back()];
if (!next.empty()) {
stack.push_back(next.top());
next.pop();
} else {
route.push_front(stack.back());
stack.pop_back();
}
}
return vector<string>(route.begin(), route.end());
}
};
More Advanced Graphs problems
- Network Delay Time (Medium)
- Evaluate Division (Medium)
- Course Schedule II (Medium)
- Alien Dictionary (Hard)
- Redundant Connection (Medium)
- Number of Connected Components (Union-Find) (Medium)
- Accounts Merge (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Min Cost to Connect All Points (Medium)
- Cheapest Flights Within K Stops (Medium)
- Bellman-Ford (negative weights) (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Strongly Connected Components (Hard)
- Minimum Height Trees (Medium)