Reconstruct Itinerary

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

We want to find a route that uses all flight ticket. The natural instinct is to use a backtracking approach. We can try constructing this route by greedily selecting the destination (smallest alphabetical destination) from a source, and when we get stuck, we backtrack to a previous location and search for the other possible routes. Since we are employing a greedy selection in this backtracking algorithm, the practical runtime should be much faster than the worst-case exponential runtime of backtracking problems.

Implementation

def findItinerary(tickets: List[List[str]]) -> List[str]:
    # set up flights graph, and unvisited counter for each (src, dst)
    flights = defaultdict(list)
    unvisited = defaultdict(int)
    tickets.sort()    # sort tickets so selection is greedy
    for src, dst in tickets:
        flights[src].append(dst)
        unvisited[(src, dst)] += 1
    
    def backtracking(src, route, unvisited):
        if len(route) == len(tickets) + 1:      # found solution
            return True
        for dst in flights[src]:
            if unvisited[(src, dst)]:           # take flight
                unvisited[(src, dst)] -= 1      # visit (src, dst)
                route.append(dst)               # update route
                if backtracking(dst, route, unvisited):
                    return True
                route.pop()                     # revert route
                unvisited[(src, dst)] += 1      # unvisit (src, dst)
        return False

    route = ['JFK']
    backtracking('JFK', route, unvisited)
    return route

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator
Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Depth first search is equivalent to which of the tree traversal order?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More