You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
Example 1:
Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] Output: ["JFK","MUC","LHR","SFO","SJC"]
Example 2:
Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order.
Constraints:
1 <= tickets.length <= 300tickets[i].length == 2fromi.length == 3toi.length == 3fromi and toi consist of uppercase English letters.fromi != toiWhen you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a stack of flight tickets and you need to arrange all of them in a continuous chain starting from a specific place. The brute force approach involves trying every single possible combination of flights until you find a complete journey that uses every ticket.
Here's how the algorithm would work step-by-step:
def find_itinerary(tickets):
ticket_stack = sorted(tickets)
# We use DFS backtracking to explore all possible ticket combinations until we find a valid Eulerian path
def depth_first_search(current_airport, current_route):
if len(current_route) == len(tickets) + 1:
return current_route
for ticket_index, flight_ticket in enumerate(ticket_stack):
departure_airport, arrival_airport = flight_ticket
if departure_airport == current_airport:
used_ticket = ticket_stack.pop(ticket_index)
current_route.append(arrival_airport)
# We recurse deeper to attempt building the rest of the itinerary with the remaining tickets
result_path = depth_first_search(arrival_airport, current_route)
if result_path:
return result_path
current_route.pop()
ticket_stack.insert(ticket_index, used_ticket)
return []
# We start our journey at JFK as required by the standard problem description
return depth_first_search("JFK", ["JFK"])To successfully plan the flight itinerary without getting stuck, we can treat the journey like a maze where we must use every single required path. By always exploring dead ends last and building our path backwards as we run out of options, we ensure we never make a wrong turn.
Here's how the algorithm would work step-by-step:
from collections import defaultdict
def find_itinerary(flight_tickets):
adjacency_list = defaultdict(list)
# Sort destinations alphabetically so we always try the lexical first choice.
for origin_airport, destination_airport in sorted(flight_tickets, reverse=True):
adjacency_list[origin_airport].append(destination_airport)
travel_route = []
exploration_stack = ["JFK"]
while exploration_stack:
current_airport = exploration_stack[-1]
# Traverse deeper into the graph only when outgoing flights still exist.
if adjacency_list[current_airport]:
next_destination = adjacency_list[current_airport].pop()
exploration_stack.append(next_destination)
else:
# Dead ends are popped and prepended to build the correct reverse path.
completed_stop = exploration_stack.pop()
travel_route.append(completed_stop)
return travel_route[::-1]| Case | How to Handle |
|---|---|
| Empty input with no tickets provided | Return a default list containing only JFK since the trip must always start from JFK. |
| Multiple valid itineraries with different lexical orders | Sort the adjacency list of destinations alphabetically to ensure the lexicographically smallest path is explored first. |
| Graph contains valid Eulerian cycles or detours | Use Hierholzers algorithm with post-order traversal to add airports to the result list only after exhausting all outgoing edges. |
| Disconnected tickets that cannot be visited from JFK | The algorithm naturally visits reachable nodes first, leaving unreachable nodes out of the final reversed path. |
| Repeated tickets between the same two airports | Treat each ticket instance as a distinct directed edge and consume them one by one as they are traversed. |
| Deep recursion depth on large valid itineraries | Use an iterative approach with an explicit stack or ensure the language stack limit accommodates up to ten thousand recursive calls. |
| Dead ends where an airport is reached with no outgoing tickets left | Post-order traversal correctly appends these dead-end airports to the end of the path before backtracking. |
| Maximum constraints with thousands of tickets | Maintain a visited state or index pointer for adjacency lists to achieve linear time complexity per edge traversal. |