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
andtoi
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 EvaluatorWhich of the following shows the order of node visit in a Breadth-first Search?
Recommended Readings
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!