Reconstruct Itinerary - Problem
Imagine you're a travel enthusiast who just returned from an amazing multi-city trip! You have a pile of airline tickets, but they're all mixed up. Your goal is to reconstruct your complete travel itinerary in the correct order.
You are given a list of airline tickets where tickets[i] = [from_i, to_i] represents the departure and arrival airports of one flight. All tickets belong to someone who started their journey from "JFK" airport.
Requirements:
- The itinerary must begin with "JFK"
- You must use all tickets exactly once
- If multiple valid itineraries exist, return the one with the smallest lexicographical order
- For example:
["JFK", "LGA"]comes before["JFK", "LGB"]
Think of this as finding an Eulerian path in a directed graph where each ticket represents an edge!
Input & Output
example_1.py β Basic Case
$
Input:
tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
βΊ
Output:
["JFK","MUC","LHR","SFO","SJC"]
π‘ Note:
Starting from JFK, we can only go to MUC. From MUC to LHR, LHR to SFO, and finally SFO to SJC. This uses all tickets exactly once.
example_2.py β Multiple Valid Paths
$
Input:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
βΊ
Output:
["JFK","ATL","JFK","SFO","ATL","SFO"]
π‘ Note:
Multiple valid itineraries exist, but we choose the lexicographically smallest: JFKβATL comes before JFKβSFO, so we start with ATL path.
example_3.py β Circular Route
$
Input:
tickets = [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]
βΊ
Output:
["JFK","NRT","JFK","KUL"]
π‘ Note:
We have two choices from JFK: KUL or NRT. Since we need to use all tickets, we must choose the path that allows us to return and use the remaining ticket.
Constraints
- 1 β€ tickets.length β€ 300
- tickets[i].length == 2
- fromi.length == 3
- toi.length == 3
- fromi and toi consist of uppercase English letters
- All tickets belong to a man who departs from "JFK"
- All tickets form at least one valid itinerary
Visualization
Tap to expand
Understanding the Visualization
1
Model as Graph
Each airport is a node, each ticket is a directed edge
2
Sort Destinations
For each airport, sort its destinations alphabetically
3
DFS with Edge Removal
Start from JFK, follow edges and remove them as we use tickets
4
Backtrack Strategy
When stuck, backtrack and record the current airport
5
Reverse Path
The recorded path is in reverse order, so flip it for the final answer
Key Takeaway
π― Key Insight: This is fundamentally an Eulerian path problem. By using Hierholzer's algorithm with DFS and careful edge removal, we can efficiently find the lexicographically smallest valid itinerary in O(E log E) time.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code