HardNo. 0332

Reconstruct Itinerary — LeetCode 332 Python Solution

Topics
Depth-First Search, Graph, Eulerian Circuit
On a study list
NeetCode 150
Reading time
2 min

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

PythonSolution
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

Related problems
No.ProblemDifficulty
0753Cracking the SafeHard
0207Course ScheduleMedium
0210Course Schedule IIMedium
0310Minimum Height TreesMedium
0399Evaluate DivisionMedium
0547Number of ProvincesMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.