Reconstruct Itinerary — LeetCode 332 Python Solution
- Problem
- #332
- Pattern
- Depth-First Search
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
- Output
- ["JFK","MUC","LHR","SFO","SJC"]
Python solution
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
def dfs(f: str):
while g[f]:
dfs(g[f].pop())
ans.append(f)
g = defaultdict(list)
for f, t in sorted(tickets, reverse=True):
g[f].append(t)
ans = []
dfs("JFK")
return ans[::-1]Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times \log m) |
| Space | O(m) auxiliary |
Pattern: Depth-First Search
Follow one path to its end before trying the next — the default way to explore a graph. LeetCode 332. Reconstruct Itinerary is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Depth-First Search and Graph.
The depth-first search guide has the Python template for the pattern and the 366 LeetCode problems that use it.
Related problems
On a study list
This problem is on NeetCode 150.
Frequently asked questions
- How hard is LeetCode 332. Reconstruct Itinerary?
- LeetCode 332. Reconstruct Itinerary is rated Hard on LeetCode.
- What is the time complexity of LeetCode 332. Reconstruct Itinerary?
- The Python solution on this page runs in O(m \times \log m).
- What is the space complexity of LeetCode 332. Reconstruct Itinerary?
- The Python solution on this page uses O(m) auxiliary space.
- What topics does LeetCode 332. Reconstruct Itinerary cover?
- LeetCode 332. Reconstruct Itinerary is tagged Depth-First Search, Graph and Eulerian Circuit on LeetCode.