Reconstruct Itinerary

Moderate
0/80
Average time to solve is 15m
profile
Contributed by
11 upvotes
Asked in companies
FacebookUberAmerican Express

Problem statement

You are given a matrix of flight 'TICKETS', where the 'i'th row represents 'i’th flight ticket. 'TICKETS'[i] = [SOURCE, DESTINATION] represents that there is a one-way flight starting from the city 'SOURCE' and ending at city 'DESTINATION'. All the flight tickets belong to a man who is initially in city "DEL".

You are supposed to reconstruct the journey satisfying the following conditions:

1. He should begin his journey from “DEL”.

2. He should use all the tickets and complete the journey.

3. He must use all the tickets only once.

Note:
1. Journey means the order in which the cities will be visited.

2. The given tickets have at least one itinerary.

3. If multiple valid itineraries are possible, then return the itinerary that is a lexicographically smallest itinerary.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer ‘T’, denoting the number of test cases. 

The first line of each test case contains integer ‘N’, which denotes the number of rows of the matrix ‘TICKET’.

The next 'N' lines contain two strings, ‘TICKET’[i][0] and ‘TICKET’[i][1], denoting that there is a flight from ‘TICKET’[i][0] to ‘TICKET’[i][1].
Output Format:
The output of each test case contains the order of cities that he should visit to satisfy the given conditions separated by space. 

The output of each test case is printed in a separate line.

Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 50
1 <= N <= 20000
0 <= M <= 20000
TICKET[i][0] != TICKET[i][1], for any valid 'i'.

Where 'M' denotes the size of the given matrix ‘TICKET’.

Time Limit: 1 sec
Sample Input 1:
1
3
DEL KUL
DEL NRT
NRT DEL
Sample Output 1:
DEL NRT DEL KUL
Explanation for Sample Input 1:
In test case 1, there are three flight tickets.

Source    -     Destination
DEL     -       KUL
DEL      -  NRT
NRT    -     DEL

In order to satisfy all the conditions, he should start from “DEL”, as per the problem statement, use ticket 2, go to “NRT”. Then come back to “DEL” using ticket 3. And then go to “KUL” using ticket 1. So the Itinerary which is possible in this case is DEL -> NRT -> DEL -> KUL.
Sample Input 2:
1
2
DEL ATL
ATL DEL
Sample Output 1:
DEL ATL DEL
Explanation for Sample Input 2:
In test case 1, there are two flight tickets.

Source  -   Destination
DEL     -    ATL
ATL     -    DEL

In order to satisfy all the conditions, he should start from “DEL”, as per the problem statement, use ticket 1, go to “ATL”. Then come back to “DEL” using ticket 2. So the Itinerary which is possible in this case is DEL -> ATL -> DEL.
Hint

Can you solve the problem by converting it into its corresponding graph? Which data structures and algorithms would be a good fit?

Approaches (1)
DFS

The idea is to represent the given tickets as a directed graph. As all the tickets form a valid route, it means the graph is a connected graph.

 

To construct the graph, we can use a hashMap in which the key will be a string and the value will be a list of strings. The key will represent the source and the values will represent the destination.

 

As we have to make the itinerary in lexicographical order. It means we have to choose the tickets in such a way that it is in sorted order. For this, we can use a multi-set list for storing the values of the hashMap.

 

For finding the itinerary, we will use Depth-first Search.

 

The steps are as follows:

 

  1. Make a directed graph named ‘GRAPH’ from the given matrix ‘ticket’.
    • Declare a hashMap with key as string and value as a multiset of strings.
    • Iterate over all the tickets:
      • Let the first element of the current row be denoted by ‘a’ and the second element of the current row be denoted by ‘b’.
      • Append ‘b’ at the end of ‘GRAPH[a]'.
  2. Initialize an array ‘ANSWER’ which stores the final answer.
  3. Define a recursive function ‘ITINERARY’, which will take three arguments - ‘GRAPH’, ‘CURRENTCITY’, ‘ANSWER’ which denotes the graph that we have created using matrix ‘TICKET', the current city, and the final array ‘ANSWER’ for storing the final answer.
  4. Iterate over all the cities ‘NEXTCITY’ that we can go from the current city:
    • Erase the ‘NEXTCITY’ from the multiset of ‘GRAPH[CURRENTCITY]' as we are going to iterate over the next city.
    • Call the recursive function ‘ITINERARY’ for the ‘NEXTCITY’.
  5. When we come out of the loop, it means we have traversed all the connected cities to the ‘CURRENTCITY' and we can not go further from the current city. So, push this city in the final answer array.
  6. The array ‘ANSWER’ stores the cities in the reverse order as for each city we insert all the neighbouring cities into the array before inserting the current city. It means “DEL”, which is the first city that will be pushed into the array at the last. So, reverse the array ‘ANSWER’.
  7. Return the array ‘ANSWER’.

 

Time Complexity

O(N * log(N)), Where ‘N’ is the number of tickets.

 

Since we are adding the elements of matrix ‘TICKET’ in the multiset(in C++) whose time complexity is log(N). In the worst case when all the flights are directed from one city to another cities the time complexity will be N * log(N). Hence, the overall time complexity is O(N * log(N)).

Space Complexity

O(N), Where ‘N’ is the number of tickets.

 

Since we are constructing a graph, for which we are using a HashMap to store the adjacent vertices for each city. The total number of edges stored in the graph will be N. Also, the dfs function will be using a recursive stack that can grow up to size N in the worst case. Hence, the overall space complexity is O(N).

Code Solution
(100% EXP penalty)
Reconstruct Itinerary
Full screen
Console