Reconstruct Itinerary — LeetCode 332 Python Solution

HardDepth-First SearchGraphEulerian Circuit
Problem
#332
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

Python
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

MeasureComplexity
TimeO(m \times \log m)
SpaceO(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.

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.

Get Stealth Interview