Build Travel Route from Airline Tickets
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests directed graph traversal, Eulerian path construction, and lexicographical ordering with Hierholzer's algorithm.
You receive a collection of airline tickets, each represented as a pair [from_airport, to_airport] indicating a one-way flight. Your task is to assemble these tickets into a complete travel route that visits every flight exactly once.
The route must satisfy these requirements:
- Begin at airport
"JFK". - Use every ticket exactly once.
- When multiple valid routes exist, return the one that is lexicographically smallest when compared as a sequence of airport codes.
You may assume a valid route always exists.
Input:
tickets: a list of ticket pairs, where each ticket is[origin, destination]with both being 3-letter uppercase airport codes.
Output:
- A list of airport codes representing the complete journey in order.
Constraints
1 <= len(tickets) <= 10,000- Each ticket contains exactly two airport codes.
- Airport codes are 3-letter uppercase strings.
- A valid solution is guaranteed to exist.
Examples
Example 1
Input: build_route([['MUC', 'LHR'], ['JFK', 'MUC'], ['SFO', 'SJC'], ['LHR', 'SFO']])
Output: ['JFK', 'MUC', 'LHR', 'SFO', 'SJC']
Example 2
Input: build_route([['JFK', 'SFO'], ['JFK', 'ATL'], ['SFO', 'ATL'], ['ATL', 'JFK'], ['ATL', 'SFO']])
Output: ['JFK', 'ATL', 'JFK', 'SFO', 'ATL', 'SFO']
Hints
Hint 1
Model the tickets as directed edges in a graph where airports are nodes. You need to find a path that uses every edge exactly once.
Hint 2
When choosing between multiple destinations from the same airport, always prefer the lexicographically smallest option. However, a greedy approach alone will fail—consider what happens if the smallest choice leads to a dead end.
Hint 3
Hierholzer's algorithm solves this by using post-order traversal: when you reach an airport with no remaining outgoing flights, record it and backtrack. The final path emerges in reverse order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model each airport as a node and each ticket as a directed edge. The problem requires finding a path that traverses every edge exactly once—this is an Eulerian path starting at "JFK".
Hierholzer's algorithm efficiently constructs such a path:
- Build an adjacency list from the tickets, sorting each destination list in descending order so removing from the end (via
pop()) yields the smallest lexicographical choice. - Starting from
"JFK", traverse edges greedily by always taking the smallest available destination. - When reaching an airport with no remaining outgoing edges, record it and backtrack to continue exploring other branches.
- The recorded airports form the path in reverse order (post-order traversal), so reverse the result at the end.
Why This Works
A naive greedy strategy fails because choosing the smallest destination first might lead to a dead end before all tickets are used. Hierholzer's algorithm handles this naturally:
- When you get stuck at an airport, that position belongs at the end of the current path segment.
- As you backtrack and explore alternative branches, those segments are correctly positioned before the dead-end airport in the final route.
- Recording airports in post-order and then reversing ensures the lexicographically smallest valid sequence.
For instance, with tickets [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]:
- The algorithm tries
JFK → KULfirst (smallest choice), hits a dead end, recordsKUL. - Backtracks to
JFK, then exploresJFK → NRT → JFK, recording those in post-order. - Reversing gives
["JFK","NRT","JFK","KUL"], which is correct despiteKUL < NRTlexicographically—going toKULfirst would strand two tickets.
Complexity
Time: O(E log E), where E is the number of tickets. Sorting each adjacency list dominates; traversal itself is O(E).
Space: O(V + E), where V is the number of airports, for the graph structure, stack, and result list.
Solution
from collections import defaultdict
from typing import List
def build_route(tickets: List[List[str]]) -> List[str]:
graph = defaultdict(list)
for origin, destination in tickets:
graph[origin].append(destination)
for origin in graph:
graph[origin].sort(reverse=True)
stack = ["JFK"]
route = []
while stack:
current = stack[-1]
if graph[current]:
stack.append(graph[current].pop())
else:
route.append(stack.pop())
return route[::-1]