It may be assumed that the input list of tickets is not cyclic and there is one ticket from every city except the final destination.
One Solution is to build a graph and do Topological Sorting of the graph. The time complexity of this solution is O(n).
We can also use hashing to avoid building a graph. The idea is to first find the starting point. A starting point would never be on ‘to’ side of a ticket. Once we find the starting point, we can simply traverse the given map to print itinerary in order. The following are steps.
1) Create a HashMap of given pair of tickets. Let the created
HashMap be 'dataset'. Every entry of 'dataset' is of the form
"from->to" like "Chennai" -> "Banglore"
2) Find the starting point of itinerary.
a) Create a reverse HashMap. Let the reverse be 'reverseMap'
Entries of 'reverseMap' are of the form "to->form".
Following is 'reverseMap' for above example.
"Delhi" -> "Bombay"
"Chennai" -> "Goa"
"Goa" -> "Delhi"
b) Traverse 'dataset'. For every key of dataset, check if it
is there in 'reverseMap'. If a key is not present, then we
found the starting point. In the above example, "Bombay" is
3) Start from above found starting point and traverse the 'dataset'
to print itinerary.
All of the above steps require O(n) time so overall time complexity is O(n).
Below is Java implementation of above idea.
voidprintItinerary(map<string, string> dataSet)
// To store reverse of given map
map<string, string> reversemap;
map<string, string>::iterator it;
// To fill reverse map, iterate through the given map