HardNo. 0332
Reconstruct Itinerary — LeetCode 332 Python Solution
- Pattern
- Depth-First Search
- Topics
- Depth-First Search, Graph, Eulerian Circuit
- On a study list
- NeetCode 150
- 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
- Time
- O(m × log m)
- Space · auxiliary
- O(m)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0753 | Cracking the Safe | Hard |
| 0207 | Course Schedule | Medium |
| 0210 | Course Schedule II | Medium |
| 0310 | Minimum Height Trees | Medium |
| 0399 | Evaluate Division | Medium |
| 0547 | Number of Provinces | Medium |
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 × 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.