Find Itinerary from a given list of tickets - GeeksforGeeks

28 Feb, 2022
Given a list of tickets, find itinerary in order using the given list.Example:  
Input:
"Chennai" -> "Banglore"
"Bombay" -> "Delhi"
"Goa"    -> "Chennai"
"Delhi"  -> "Goa"

Output: 
Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore,
It may be assumed that the input list of tickets is not cyclic and there is one ticket from every city except final destination.One Solution is to build a graph and do Topological Sorting of the graph. 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. 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.
        "Banglore"-> "Chennai" 
        "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
        starting point.

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. 
Java
C++
Python3
Javascript
// Java program to print itinerary in orderimport java.util.HashMap;import java.util.Map; public class printItinerary{    // Driver function    public static void main(String[] args)    {        Map<String, String> dataSet = new HashMap<String, String>();        dataSet.put("Chennai", "Banglore");        dataSet.put("Bombay", "Delhi");        dataSet.put("Goa", "Chennai");        dataSet.put("Delhi", "Goa");         printResult(dataSet);    }     // This function populates 'result' for given input 'dataset'    private static void printResult(Map<String, String> dataSet)    {        // To store reverse of given map        Map<String, String> reverseMap = new HashMap<String, String>();         // To fill reverse map, iterate through the given map        for (Map.Entry<String,String> entry: dataSet.entrySet())            reverseMap.put(entry.getValue(), entry.getKey());         // Find the starting point of itinerary        String start = null;        for (Map.Entry<String,String> entry: dataSet.entrySet())        {              if (!reverseMap.containsKey(entry.getKey()))              {                   start = entry.getKey();                   break;              }        }         // If we could not find a starting point, then something wrong        // with input        if (start == null)        {           System.out.println("Invalid Input");           return;        }         // Once we have starting point, we simple need to go next, next        // of next using given hash map        String to = dataSet.get(start);        while (to != null)        {            System.out.print(start +  "->" + to + ", ");            start = to;            to = dataSet.get(to);        }    }}
#include <bits/stdc++.h>using namespace std; void printItinerary(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    for (it = dataSet.begin(); it!=dataSet.end(); it++)        reversemap[it->second] = it->first;     // Find the starting point of itinerary    string start;     for (it = dataSet.begin(); it!=dataSet.end(); it++)    {        if (reversemap.find(it->first) == reversemap.end())        {            start = it->first;            break;        }    }     // If we could not find a starting point, then something wrong with input     if (start.empty())     {        cout << "Invalid Input" << endl;        return;     }     // Once we have starting point, we simple need to go next,    //next of next using given hash map    it = dataSet.find(start);    while (it != dataSet.end())    {        cout << it->first << "->" << it->second << endl;        it = dataSet.find(it->second);    } } int main(){    map<string, string> dataSet;    dataSet["Chennai"] = "Banglore";    dataSet["Bombay"] = "Delhi";    dataSet["Goa"] = "Chennai";    dataSet["Delhi"] = "Goa";     printItinerary(dataSet);     return 0;}// C++ implementation is contributed by Aditya Goel
class Solution():    #Solution class carries method for printing itinerary    def __init__(self):        pass    #method for printing itinerary    def printitinerary(self,d):        # First step : create a reversed mapping. Here also for storing key value pairs dictionary is used.        reverse_d = dict()        for i in d:            reverse_d[d[i]] = i        # Second step : find the starting point. Starting point will be that value which is not present in 'd' as key.        for i in reverse_d:            if reverse_d[i] not in reverse_d:                starting_pt = reverse_d[i]                break;        #Third step : simply proceed one by one to print whole route. Assuming that there exist Starting point.        while(starting_pt in d):            print(starting_pt,"->",d[starting_pt],end=", ")            starting_pt = d[starting_pt]        #method prints here only. Does not return anything.  if __name__=="__main__":    # Mapping using inbuilt data structure 'dictionary'    d = dict()    d["Chennai"] = "Banglore"    d["Bombay"] = "Delhi"    d["Goa"] = "Chennai"    d["Delhi"] = "Goa"     # call for method that would print itinerary.    obj = Solution()    obj.printIterary(d)
// JavaScript approach to sollve the problem function printItinerary(dataSet){    // To store reverse of given map    let reversemap = new Map();     // To fill reverse map, iterate through the given map    for (const[key,value] of dataSet)        reversemap.set(value,key);     // Find the starting point of itinerary    let start = "";     for (const key of dataSet.keys())    {        if (!reversemap.has(key))        {            start = key;            break;        }    }     // If we could not find a starting point, then something wrong with input     if (start.length == 0)     {        console.log("Invalid Input");        return;     }     // Once we have starting point, we simple need to go next,    //next of next using given hash map    let it = start;    while (dataSet.has(it))    {        console.log(it+"->"+dataSet.get(it));        it = dataSet.get(it);    } } // driver code let dataSet = new Map();dataSet.set("Chennai","Banglore");dataSet.set("Bombay","Delhi");dataSet.set("Goa","Chennai");dataSet.set("Delhi","Goa");printItinerary(dataSet); //code is contributed by shinjanpatra
Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore, 
 
YouTubeGeeksforGeeks502K subscribersFind Itinerary from a given list of tickets (Tickets Hashing)| GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:22•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=u52i2gAnFvU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is compiled by Rahul Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
20ajinky
shinjanpatra
surinderdawra388
Topological Sorting
Hash
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Quadratic Probing in Hashing
Rearrange an array such that arr[i] = i
Hashing in Java
Non-Repeating Element
What are Hash Functions and How to choose a good Hash Function?
Advantages of BST over Hash Table
Find duplicates in a given array when elements are not limited to a range
Real-time application of Data Structures
Largest subarray with equal number of 0s and 1s
Index Mapping (or Trivial Hashing) with negatives allowed