Given a list of departure and arrival airports, find the itinerary in order. It may be assumed that departure is scheduled from every airport except the final destination, and each airport is visited only once, i.e., there are no cycles in the route.

For example,

Input:
 
HKG —> DXB
FRA —> HKG
DEL —> FRA
 
Output: DEL —> FRA —> HKG —> DXB
 
 
Input:
 
LAX —> DXB
DFW —> JFK
LHR —> DFW
JFK —> LAX
 
Output: LHR —> DFW —> JFK —> LAX —> DXB

Practice this problem

We can easily solve this problem in linear time using hashing. The idea is to find the source airport and print the itinerary starting from the source airport. To find the source airport, construct a set of destination airports from a given list of tickets. A source airport would be one that is not present in the list of destination airports. Once the source airport is found, traverse the list of tickets to the print itinerary in order using recursion.

Following is the C++, Java, and Python program that demonstrates this:

C++


Download  Run Code

Output:

LHR —> DFW
DFW —> JFK
JFK —> LAX
LAX —> DXB

Java


Download  Run Code

Output:

LHR —> DFW
DFW —> JFK
JFK —> LAX
LAX —> DXB

Python


Download  Run Code

Output:

LHR —> DFW
DFW —> JFK
JFK —> LAX
LAX —> DXB

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the total number of tickets.

 
Another standard solution is to build a directed graph of departure to arrival airports and perform topological sorting upon it. The time complexity of this solution remains O(n).