KatInterview

332. Reconstruct Itinerary

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to reconstruct a travel itinerary from a given list of flight tickets. The key constraints are:

Solution

Reconstruct Itinerary in Python

import collections

class Solution:
    def findItinerary(self, tickets: list[list[str]]) -> list[str]:
        # Create an adjacency list.
        adj = collections.defaultdict(list)
        # We sort tickets in reverse order initially to make it slightly more efficient
        # to build the reverse-sorted adjacency lists. An alternative is to sort after building.
        for src, dst in sorted(tickets, reverse=True):
            adj[src].append(dst)

        itinerary = []

        def dfs(airport):
            # Visit all destinations from the current airport.
            # We pop from the end of the list, which is the smallest
            # destination due to the reverse sort.
            while adj[airport]:
                next_airport = adj[airport].pop()
                dfs(next_airport)
            
            # After visiting all destinations, add the airport to the itinerary.
            # This post-order traversal builds the path backwards.
            itinerary.append(airport)

        # Start the DFS from "JFK".
        dfs("JFK")

        # The itinerary is constructed in reverse, so we need to reverse it at the end.
        return itinerary[::-1]

Reconstruct Itinerary in Java

class Solution {
    // Adjacency list. Using a PriorityQueue to automatically handle lexical order of destinations.
    private Map<String, PriorityQueue<String>> adj = new HashMap<>();
    // The result itinerary, built in reverse order.
    private LinkedList<String> itinerary = new LinkedList<>();

    public List<String> findItinerary(List<List<String>> tickets) {
        // Build the graph.
        for (List<String> ticket : tickets) {
            String from = ticket.get(0);
            String to = ticket.get(1);
            // computeIfAbsent ensures the PriorityQueue is initialized if not present.
            adj.computeIfAbsent(from, k -> new PriorityQueue<>()).add(to);
        }

        // Start the DFS from "JFK".
        dfs("JFK");

        return itinerary;
    }

    private void dfs(String airport) {
        // While there are destinations from the current airport.
        // The check adj.containsKey(airport) is important for airports that are only destinations.
        while (adj.containsKey(airport) && !adj.get(airport).isEmpty()) {
            // Poll the smallest lexical destination from the priority queue.
            String nextAirport = adj.get(airport).poll();
            dfs(nextAirport);
        }
        // Add the current airport to the front of the list.
        // This is where the post-order traversal logic happens. An airport is added only
        // after all its departure routes are explored. This builds the path backwards.
        itinerary.addFirst(airport);
    }
}

Reconstruct Itinerary in C++

class Solution {
public:
    vector<string> findItinerary(vector<vector<string>>& tickets) {
        // Adjacency list using a multiset to keep destinations sorted lexicographically.
        unordered_map<string, multiset<string>> adj;
        for (const auto& ticket : tickets) {
            adj[ticket[0]].insert(ticket[1]);
        }

        vector<string> itinerary;
        // The path is constructed backwards, so we use a stack-like approach.
        function<void(string)> dfs = [&](string airport) {
            // Visit all destinations from the current airport.
            while (!adj[airport].empty()) {
                // Get the lexicographically smallest destination.
                string next_airport = *adj[airport].begin();
                // Remove the ticket (edge) to avoid using it again.
                adj[airport].erase(adj[airport].begin());
                dfs(next_airport);
            }
            // After visiting all destinations, add the current airport to the path.
            // This post-order traversal ensures we only add an airport when it's a dead end
            // in the remaining graph, thus building the path backwards.
            itinerary.push_back(airport);
        };

        // Start the DFS from "JFK".
        dfs("JFK");

        // The itinerary was built in reverse, so reverse it to get the correct order.
        reverse(itinerary.begin(), itinerary.end());
        return itinerary;
    }
};

Reconstruct Itinerary in TypeScript

function findItinerary(tickets: string[][]): string[] {
    // Adjacency list to represent the graph.
    const adj = new Map<string, string[]>();

    // Build the graph from the tickets.
    for (const [from, to] of tickets) {
        if (!adj.has(from)) {
            adj.set(from, []);
        }
        adj.get(from)!.push(to);
    }

    // Sort the destinations for each airport in reverse lexical order.
    // This allows us to use pop() which is O(1) to get the smallest element.
    for (const destinations of adj.values()) {
        destinations.sort((a, b) => b.localeCompare(a));
    }

    const itinerary: string[] = [];

    // Recursive DFS function.
    function dfs(airport: string) {
        const destinations = adj.get(airport);

        // Visit all destinations from the current airport.
        while (destinations && destinations.length > 0) {
            // Get the smallest lexical destination.
            const nextAirport = destinations.pop()!;
            dfs(nextAirport);
        }

        // After exploring all routes, add the airport to the itinerary.
        // This post-order addition constructs the path backwards.
        itinerary.push(airport);
    }

    // Start the process from "JFK".
    dfs("JFK");

    // Reverse the result to get the correct itinerary order.
    return itinerary.reverse();
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.