We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Reconstruct Itinerary

Number: 332

Difficulty: Hard

Paid? No

Companies: Pinterest, Amazon, Google, Yandex, Bloomberg, Meta, Flipkart, Twilio, Uber, Snap, Booking.com, eBay


Problem Description

Given a list of airline tickets represented as [from, to] pairs, reconstruct the itinerary such that:

  • The itinerary begins with "JFK".
  • Every ticket is used exactly once.
  • If multiple valid itineraries exist, return the one with the smallest lexical order when concatenated as a single string.

Key Insights

  • Model the tickets as a directed graph where airports are nodes.
  • The problem is akin to finding an Eulerian path through the graph.
  • Use Depth-First Search (DFS) with Hierholzer’s algorithm to construct the itinerary.
  • To ensure lexical order, sort the destination lists in reverse order so that the smallest lexical destination can be popped during DFS.
  • Build the itinerary in reverse during backtracking and then reverse it to get the final order.

Space and Time Complexity

Time Complexity: O(E log E), where E is the number of tickets, due to the sorting of edges. Space Complexity: O(E), to store the graph and recursion stack.


Solution

Construct an adjacency list (graph) mapping each departure airport to a list of destination airports sorted in reverse lexicographical order. Perform DFS starting from "JFK". During DFS, traverse while there are destinations available from the current airport. Append airports to the itinerary as you backtrack. Reverse the built itinerary at the end to obtain the correct order.


Code Solutions

def findItinerary(tickets):
    # Build the graph as an adjacency list.
    graph = {}
    for src, dst in tickets:
        if src not in graph:
            graph[src] = []
        graph[src].append(dst)
    # Sort the destination lists in reverse lexicographical order.
    for src in graph:
        graph[src].sort(reverse=True)
    
    itinerary = []
    
    def dfs(airport):
        # Explore all flights out of the current airport.
        while airport in graph and graph[airport]:
            next_dest = graph[airport].pop()
            dfs(next_dest)
        itinerary.append(airport)
    
    # Start DFS from 'JFK'
    dfs("JFK")
    # The itinerary is constructed in reverse.
    return itinerary[::-1]

# Example usage:
tickets = [["JFK","SFO"], ["JFK","ATL"], ["SFO","ATL"], ["ATL","JFK"], ["ATL","SFO"]]
print(findItinerary(tickets))
← Back to All Questions