Taro Logo

Reconstruct Itinerary

#1 Most AskedHard
1 view
Topics:
Graphs

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.

All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.

  • For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].

You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.

Example 1:

Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
Output: ["JFK","MUC","LHR","SFO","SJC"]

Example 2:

Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order.

Constraints:

  • 1 <= tickets.length <= 300
  • tickets[i].length == 2
  • fromi.length == 3
  • toi.length == 3
  • fromi and toi consist of uppercase English letters.
  • fromi != toi

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Is it guaranteed that a valid itinerary always exists using all the provided tickets, or could we receive a set of tickets where no complete Eulerian path is possible?
  2. Can there be duplicate tickets (i.e., multiple identical flights from the same departure to the same arrival airport), and if so, must we use each individual ticket instance separately?
  3. How should we handle disconnected flights or dead ends where we might visit all tickets in one branch but get stuck before using others, or does the problem guarantee we can always form a complete valid tour?
  4. Are all airport codes guaranteed to be uppercase 3-letter strings, and should we expect any malformed inputs like empty lists or missing 'JFK'?
  5. When the problem states to return the itinerary with the 'smallest lexical order', does that mean at each choice point we should greedily pick the alphabetically smallest destination airport, or evaluate the full string concatenation lexicographically?

Brute Force Solution

Approach

Imagine you have a stack of flight tickets and you need to arrange all of them in a continuous chain starting from a specific place. The brute force approach involves trying every single possible combination of flights until you find a complete journey that uses every ticket.

Here's how the algorithm would work step-by-step:

  1. Begin at the required starting airport with all your available tickets.
  2. Look at all the flights you can take from your current location.
  3. Pick one available flight and mentally travel to that next destination, setting that ticket aside.
  4. Repeat this process, picking the next available flight from your new location, until you either run out of flights or get stuck.
  5. Check if you managed to use every single ticket in your starting stack during this attempt.
  6. If you successfully used every ticket, you have found a valid travel plan.
  7. If you ran out of flights before using all your tickets, erase this attempt, go back a few steps, and try a different flight order.
  8. Keep trying different combinations of ticket sequences until you successfully build a complete journey using every ticket.

Code Implementation

def find_itinerary(tickets):
    ticket_stack = sorted(tickets)
    
    # We use DFS backtracking to explore all possible ticket combinations until we find a valid Eulerian path
    def depth_first_search(current_airport, current_route):
        if len(current_route) == len(tickets) + 1:
            return current_route

        for ticket_index, flight_ticket in enumerate(ticket_stack):
            departure_airport, arrival_airport = flight_ticket
            if departure_airport == current_airport:
                used_ticket = ticket_stack.pop(ticket_index)
                current_route.append(arrival_airport)
                
                # We recurse deeper to attempt building the rest of the itinerary with the remaining tickets
                result_path = depth_first_search(arrival_airport, current_route)
                if result_path:
                    return result_path

                current_route.pop()
                ticket_stack.insert(ticket_index, used_ticket)

        return []

    # We start our journey at JFK as required by the standard problem description
    return depth_first_search("JFK", ["JFK"])

Big(O) Analysis

Time Complexity
O(d^n) – In the worst-case scenario where we explore the graph of tickets recursively, at each step we have a branching factor of d representing available outbound flights and a maximum depth of n representing the total number of tickets. Trying and backtracking through different flight combinations requires exploring paths whose length is proportional to the number of tickets. This recursive trial-and-error process leads to an exponential number of paths proportional to d raised to the power of n. Therefore, the total operations approximate d to the power of n, which simplifies to O(d^n).
Space Complexity
O(N) – Let N represent the total number of flight tickets provided in the input stack. The auxiliary space is driven by the hash map storing the adjacency list of all destinations, the recursion stack frames reaching a maximum depth of N plus one during the depth-first search, and the final itinerary list holding all N plus one airport stops. These combined data structures scale linearly with the number of tickets, leading to an overall auxiliary space complexity of O(N).

Optimal Solution

Approach

To successfully plan the flight itinerary without getting stuck, we can treat the journey like a maze where we must use every single required path. By always exploring dead ends last and building our path backwards as we run out of options, we ensure we never make a wrong turn.

Here's how the algorithm would work step-by-step:

  1. Organize all the available flight tickets so that destinations leaving from the same starting point are arranged in alphabetical order.
  2. Begin your journey at the mandatory starting airport.
  3. Look at the available flights leaving your current location and pick the very first alphabetical destination.
  4. Keep taking flights this way, always choosing the first available alphabetical option, until you reach an airport that has no outgoing flights left.
  5. When you get stuck at an airport with no remaining flights, add this final stop to the very front of your finished travel plan.
  6. Step backward to the previous airport you visited and check if it has any other unused flights remaining.
  7. Repeat this exploration process for any remaining flights, continuously adding newly discovered dead-end stops to the beginning of your growing travel plan until every single ticket has been used.

Code Implementation

from collections import defaultdict


def find_itinerary(flight_tickets):
    adjacency_list = defaultdict(list)
    
    # Sort destinations alphabetically so we always try the lexical first choice.
    for origin_airport, destination_airport in sorted(flight_tickets, reverse=True):
        adjacency_list[origin_airport].append(destination_airport)

    travel_route = []
    exploration_stack = ["JFK"]

    while exploration_stack:
        current_airport = exploration_stack[-1]
        
        # Traverse deeper into the graph only when outgoing flights still exist.
        if adjacency_list[current_airport]:
            next_destination = adjacency_list[current_airport].pop()
            exploration_stack.append(next_destination)
        else:
            # Dead ends are popped and prepended to build the correct reverse path.
            completed_stop = exploration_stack.pop()
            travel_route.append(completed_stop)

    return travel_route[::-1]

Big(O) Analysis

Time Complexity
O(E log E) – Building the graph requires processing each of the E tickets and sorting the destinations for each airport alphabetically, which takes O(E log (E / V)) time. During the depth-first traversal using Hierholzer's algorithm, every single ticket is traversed exactly once, resulting in O(E) steps for the edge exploration. Combining the sorting phase and the traversal phase, the total operations scale with the number of tickets. This simplifies to a worst-case time complexity of O(E log E).
Space Complexity
O(N) – To analyze the space complexity, let N represent the total number of flight tickets provided in the input. The algorithm relies on several auxiliary data structures: a hash map (or adjacency list) storing all N tickets, a recursive call stack or iterative stack that can grow up to a depth of N plus one frames, and a final route list that holds N plus one airport names. Because each of these data structures scales in direct proportion to the number of tickets, the total extra memory consumed grows linearly. Simplifying this to Big O notation yields an overall auxiliary space complexity of O(N).

Edge Cases

Empty input with no tickets provided
How to Handle:
Return a default list containing only JFK since the trip must always start from JFK.
Multiple valid itineraries with different lexical orders
How to Handle:
Sort the adjacency list of destinations alphabetically to ensure the lexicographically smallest path is explored first.
Graph contains valid Eulerian cycles or detours
How to Handle:
Use Hierholzers algorithm with post-order traversal to add airports to the result list only after exhausting all outgoing edges.
Disconnected tickets that cannot be visited from JFK
How to Handle:
The algorithm naturally visits reachable nodes first, leaving unreachable nodes out of the final reversed path.
Repeated tickets between the same two airports
How to Handle:
Treat each ticket instance as a distinct directed edge and consume them one by one as they are traversed.
Deep recursion depth on large valid itineraries
How to Handle:
Use an iterative approach with an explicit stack or ensure the language stack limit accommodates up to ten thousand recursive calls.
Dead ends where an airport is reached with no outgoing tickets left
How to Handle:
Post-order traversal correctly appends these dead-end airports to the end of the path before backtracking.
Maximum constraints with thousands of tickets
How to Handle:
Maintain a visited state or index pointer for adjacency lists to achieve linear time complexity per edge traversal.
0/1 completed