Open In App

Find Itinerary from a given list of tickets

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 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.
        "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.

C++




#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


Java




// Java program to print itinerary in order
import 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);
        }
    }
}


Python3




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.printItinerary(d)


C#




// C# program to print itinerary in order
using System;
using System.Collections.Generic;
  
public class printItinerary
{
  // Driver function
  public static void Main(string[] args)
  {
    Dictionary<string, string> dataSet = new Dictionary<string, string>();
    dataSet["Chennai"] = "Banglore";
    dataSet["Bombay"] = "Delhi";
    dataSet["Goa"] = "Chennai";
    dataSet["Delhi"] = "Goa";
  
    printResult(dataSet);
  }
  
  // This function populates 'result' for given input 'dataset'
  private static void printResult( Dictionary<string, string> dataSet)
  {
  
    // To store reverse of given map
    Dictionary<string, string> reverseMap = new  Dictionary<string, string>();
  
    // To fill reverse map, iterate through the given map
    foreach (var entry in dataSet)
      reverseMap[entry.Value] = entry.Key;
  
    // Find the starting point of itinerary
    string start = null;
    foreach (var entry in dataSet)
    {
      if (!reverseMap.ContainsKey(entry.Key))
      {
        start = entry.Key;
        break;
      }
    }
  
    // If we could not find a starting point, then something wrong
    // with input
    if (start == null)
    {
      Console.WriteLine("Invalid Input");
      return;
    }
  
    // Once we have starting point, we simple need to go next, next
    // of next using given hash map
    string to = dataSet[start];
    while (true
    {
      Console.Write(start +  "->" + to + ", ");
      start = to;
      if (!dataSet.ContainsKey(to))
        break;
      to = dataSet[to];
    }
  }
}
  
  
// This code is contributed by phasing17


Javascript




// 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


Output

Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore, 

Time Complexity: O(n).
Auxiliary Space: O(n), The extra space is used in map.



Previous Article
Next Article

Similar Reads

Find the maximum amount that can be collected by selling movie tickets
Given an integer N and an array seats[] where N is the number of people standing in a line to buy a movie ticket and seat[i] is the number of empty seats in the ith row of the movie theater. The task is to find the maximum amount a theater owner can make by selling movie tickets to N people. Price of a ticket is equal to the maximum number of empty
7 min read
Maximize the profit after selling the tickets
Given array seats[] where seat[i] is the number of vacant seats in the ith row in a stadium for a cricket match. There are N people in a queue waiting to buy the tickets. Each seat costs equal to the number of vacant seats in the row it belongs to. The task is to maximize the profit by selling the tickets to N people. Examples: Input: seats[] = {2,
10 min read
Maximize the profit after selling the tickets | Set 2 (For elements in range [1, 10^6])
Given an array, arr[] of size N where arr[i] represents the number of tickets, the ith seller has and a positive integer K. The price of a ticket is the number of tickets remaining with the ticket seller. They can sell a total of K tickets. Find the maximum amount they can earn by selling K tickets. Give the answer modulo 109 + 7. Examples: Input:
11 min read
CSES Solutions - Concert Tickets
There are N concert tickets available, each with a certain price given as array tickets[]. Then, M customers arrive, one after another. Each customer announces the maximum price they are willing to pay for a ticket given as array customer[], and after this, they will get a ticket with the nearest possible price such that it does not exceed the maxi
5 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] Method #1 : Using pow() function.We can use list compreh
5 min read
Create new linked list from two given linked list with greater element at each node
Given two linked list of the same size, the task is to create a new linked list using those linked lists. The condition is that the greater node among both linked list will be added to the new linked list.Examples: Input: list1 = 5-&gt;2-&gt;3-&gt;8 list2 = 1-&gt;7-&gt;4-&gt;5 Output: New list = 5-&gt;7-&gt;4-&gt;8 Input: list1 = 2-&gt;8-&gt;9-&gt;
8 min read
Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
Given a Linked List of even number of nodes, the task is to generate a new Linked List such that it contains the maximum difference of squares of node values in decreasing order by including each node in a single pair. Examples: Input: 1 -&gt; 6 -&gt; 4 -&gt; 3 -&gt; 5 -&gt;2Output: 35 -&gt; 21 -&gt; 7Explanation:The difference between squares of 6
11 min read
Partitioning a linked list around a given value and If we don't care about making the elements of the list "stable"
Given a linked list and a value x, partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not
8 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7&lt; – &gt; 6 &lt; – &gt; 8 &lt; – &gt; 11 &lt; – &gt; 3, K = 3 Output: 8 &lt; – &gt; 6 &lt; – &gt; 7 &lt; – &gt; 3 &lt; – &gt; 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 &lt; – &gt; 6
13 min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 &lt;-&gt; 7 &lt;-&gt; 9 &lt;-&gt; 7Output: 7 &lt;-&gt; 4 &lt;-&gt; 7 &lt;-&gt; 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 &lt;
12 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg