Python 0332.py
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
next = defaultdict(list)
count = defaultdict(int)
for a, b in tickets:
next[a].append(b)
count[a + b] += 1
for n in next:
next[n] = sorted(set(next[n]))
def deeper(city):
for n in next[city]: # sorted order
flight = city + n
if count[flight] > 0:
count[flight] -= 1
plan = deeper(n)
if plan:
return [ city ] + plan
count[flight] += 1
# final
if sum(count.values()) == 0:
return [ city ]
return None
return deeper("JFK")
Difficulty
and has an acceptance rate of about 45% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Depth First Search
- Eulerian Circuit
- Graph Theory
- Heap (Priority Queue)
- Sorting
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic itinerary reconstruction problem: given a list of airline tickets represented as departure-arrival pairs, it must produce a travel route that uses every ticket exactly once, starts at “JFK”, and follows lexical order when multiple choices exist. The algorithm builds adjacency information, enforces lexical ordering, and then performs a depth-first search with backtracking to assemble a valid itinerary.
Data structures
The solution relies on two defaultdict containers. The first maps each departure city to a list of its reachable destinations. The second records how many times a specific directed edge appears in the input, using the concatenated string of departure and arrival as a unique key. This edge counter enables the algorithm to handle duplicate tickets correctly.
next = defaultdict(list)
count = defaultdict(int)
for a, b in tickets:
next[a].append(b)
count[a + b] += 1
Sorting destinations
After populating the adjacency list, each city’s destination list is transformed into a sorted set. Converting to a set removes duplicate entries, while sorting guarantees that the recursive search explores destinations in lexical order, satisfying the problem’s ordering requirement.
for n in next:
next[n] = sorted(set(next[n]))
Recursive depth-first search with backtracking
The core of the algorithm is the nested deeper function. It receives the current city and attempts to extend the itinerary by iterating over the pre-sorted destinations. For each candidate destination, it checks the edge counter; a positive count indicates that an unused ticket for that leg exists. The counter is decremented before recursing, and if the recursive call yields a complete plan, the current city is prepended to that plan and returned. If the recursive branch fails, the counter is restored, effectively backtracking.
def deeper(city):
for n in next[city]: # iterate in lexical order
flight = city + n
if count[flight] > 0:
count[flight] -= 1
plan = deeper(n)
if plan:
return [city] + plan
count[flight] += 1
Detecting a complete itinerary
When the loop over outgoing flights finishes without finding a viable continuation, the function checks whether all tickets have been consumed. This is done by summing the remaining values in the edge counter. If the sum is zero, the current city represents the final stop, and a list containing only that city is returned. Otherwise, the function returns None to signal that the current path cannot lead to a full solution.
# final
if sum(count.values()) == 0:
return [city]
return None
Initiating the search
The public method simply invokes deeper starting from “JFK”, which is the mandated origin. The returned list from deeper constitutes the complete itinerary.
return deeper("JFK")
Edge cases addressed
The implementation gracefully handles several subtle scenarios:
-
Multiple identical tickets - By storing the number of occurrences of each directed edge in
count, the algorithm can differentiate between distinct tickets that share the same departure and arrival cities. The decrement-and-restore pattern ensures each copy is used exactly once. -
Cities with no outgoing flights - If a city appears only as a destination, it will not have an entry in the adjacency map. The loop over
next[city]simply does not execute, and the function proceeds to the final-state check, allowing the algorithm to correctly terminate at such leaf nodes. -
Disconnected components - The sum-check on
countguarantees that the recursion only succeeds when every ticket, regardless of its connectivity, has been consumed. Paths that leave unused tickets are rejected, preventing premature termination. -
Lexical ordering ties - Because each city’s destination list is a sorted set, the recursion always explores the smallest lexical option first. This deterministic ordering ensures that, when multiple valid itineraries exist, the one that is lexicographically smallest is produced.
-
Self-loops - Tickets where departure and arrival are the same city are treated like any other edge; the counter tracks their usage, and the recursion can traverse them without special handling.
Performance optimizations
Several design choices contribute to efficient execution:
-
Use of
defaultdict- This eliminates the need for explicit existence checks when populating adjacency and count structures, reducing overhead in the initial loop. -
Deduplication before sorting - Converting each destination list to a set removes duplicate entries prior to sorting, decreasing the number of elements the recursive loop must iterate over. This is especially beneficial when many identical tickets exist for a single departure city.
-
Early pruning via edge counter - Before recursing, the algorithm verifies that a ticket for the candidate flight remains unused. This prevents unnecessary recursive calls down paths that are already exhausted, cutting down the search space.
-
Backtracking with in-place counter restoration - Rather than copying the entire counter map for each recursive call, the code mutates the counter in place and restores it on failure. This approach keeps memory usage low and avoids the cost of deep copies.
-
Termination check based on aggregate count - The final-state test uses a single
sum(count.values())call to determine whether all tickets have been used. This avoids scanning individual adjacency lists for emptiness and provides a quick exit condition when a complete itinerary is found.
Together, these techniques enable the solution to explore the combinatorial space of ticket permutations efficiently while respecting the lexical ordering constraint.
ELI5 - Simplified Explanation
Imagine a big map with lots of cities and airplanes waiting to fly. This code is like a travel planner that figures out how to visit every single place using all the available tickets without leaving any behind.
First, the code organizes all the tickets by looking at where each flight starts and where it goes. It puts these destinations into little groups so it is easy to find the next stop. It also keeps a tally of how many times it can fly between two cities.
Then, there is a special helper that acts like a curious explorer. This explorer starts at an airport called JFK and looks at all the possible flights from there. It picks one, flies to a new city, and tries to keep going from there. If the explorer gets stuck and still has tickets left over, it goes back and tries a different flight instead.
This happens over and over, just like following a maze, until every ticket has been used up and the path is finished. The program remembers the sequence of cities visited throughout the whole adventure and keeps that list as the final result.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| FelixFan1122 | Java | |||||||||
| fengvyi | C++ | |||||||||
| Garvit244 | Python | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | Python | |||||||||
| XiaotaoGuo | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| FelixFan1122 | Java | |||||||||
| fengvyi | C++ | |||||||||
| Garvit244 | Python | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | Python | |||||||||
| XiaotaoGuo | C++ | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 1923: Longest Common Subpath
- problem 2097: Valid Arrangement of Pairs
Solved On The Same Day
- problem 1218: Longest Arithmetic Subsequence of Given Difference
- problem 1631: Path With Minimum Effort
- problem 329: Longest Increasing Path in a Matrix
- problem 1312: Minimum Insertion Steps to Make a String Palindrome
- problem 1964: Find the Longest Valid Obstacle Course at Each Position
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality