You are given a list of allowed itineraries between cities. Each itinerary represents a directed route from one city to another city.
Design an algorithm to find the longest route that can be formed using the given itineraries. A route may start from any city and must follow only the given directed itineraries.
The length of a route is measured by the number of cities visited in that route. Return the route that visits the maximum number of cities.
"source,destination"."Mumbai,Pune" means there is a directed route from Mumbai to Pune."->"."Mumbai->Pune->Delhi".String findLongestItineraryRoute(List<String> allowedItineraries)
0 ≤ allowedItineraries.size() ≤ 100,0001 ≤ source.length() ≤ 1001 ≤ destination.length() ≤ 100source != destination for every itinerary string.Method call:
findLongestItineraryRoute(allowedItineraries = List.of("Mumbai,Pune", "Pune,Indore", "Indore,Delhi", "Pune,Delhi"))
Output:
"Mumbai->Pune->Indore->Delhi"
Explanation:
The route visits 4 cities, which is the maximum possible.
Method call:
findLongestItineraryRoute(allowedItineraries = List.of("A,B", "A,C", "B,D", "C,D"))
Output:
"A->B->D"
Explanation:
Both A->B->D and A->C->D visit 3 cities. Since "A->B->D" is lexicographically smaller, it is returned.
Method call:
findLongestItineraryRoute(allowedItineraries = List.of("Delhi,Agra", "Goa,Mumbai", "Mumbai,Pune", "Pune,Nashik"))
Output:
"Goa->Mumbai->Pune->Nashik"
Explanation:
The input contains disconnected groups of cities. The returned route visits the maximum number of cities.
Method call:
findLongestItineraryRoute(allowedItineraries = List.of("A,B", "A,B", "B,C"))
Output:
"A->B->C"
Explanation:
The duplicate itinerary "A,B" is treated as a single directed itinerary.
Method call:
findLongestItineraryRoute(allowedItineraries = List.of())
Output:
""
Explanation:
There are no allowed itineraries, so no route can be formed.