Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and
arrival airports [from, to]
, reconstruct the itinerary in
order. All of the tickets belong to a man who departs from
JFK
. Thus, the itinerary must begin with
JFK
.
Note:
-
If there are multiple valid itineraries, you should return the
itinerary that has the smallest lexical order when read as a single
string. For example, the itinerary
["JFK", "LGA"]
has a smaller lexical order than["JFK", "LGB"]
. - All airports are represented by three capital letters (IATA code).
- You may assume all tickets form at least one valid itinerary.
- One must use all the tickets once and only once.
Example 1:
Input:
[["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output:["JFK", "MUC", "LHR", "SFO", "SJC"]
Example 2:
Input:
[["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output:["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is["JFK","SFO","ATL","JFK",
. But it is larger in lexical order.
"ATL","SFO"]
class Solution {
Map<String,
PriorityQueue<String>> map = new HashMap<>();
LinkedList<String> list = new LinkedList<>();
public List<String>
findItinerary(List<List<String>> t) {
for(List<String> e : t){
String from = e.get(0), to = e.get(1);
if(!map.containsKey(from))
map.put(from, new PriorityQueue<>());
map.get(from).add(to);
}
itineraryHelper("JFK");
return list;
}
private void itineraryHelper(String str){
PriorityQueue<String> pq = map.get(str);
while(pq != null && !pq.isEmpty())
itineraryHelper(pq.poll());
list.addFirst(str);
}
}
Here, we are going to create graph using Map with string as key and
priority queue as value(inorder to store in lexical order). We
can also try using TreeSet but there is a possibility of multiple
tickets for (u,v).
1) Store source and destinations in a map. If a source is already
present, then add destination to PriorityQueue. Else add a source to
map and create a new PriorityQueue with destination.
2) Call itineraryHelper() from "JFK"
3) From this method, with help of PriorityQueue add all destinations
to result list in lexical order(already stored in map)
This problem is application of
Eulerian Path
Related Posts:
Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation
Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation
Click Follow button to receive updates from us instantly.
Please let us know about your views in comment section.
Comments
Post a Comment