Reconstruct Itinerary
Put a traveller's tickets back in flight order, starting at JFK and using each ticket once.
Given a list of airline tickets, each written as [from, to]"JFK"
Example 1
Output: ["JFK","MUC","LHR","SFO","SJC"]
Example 2
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Example 3
Output: ["JFK","NRT","JFK","KUL"]
Explanation: KUL comes before NRT in the alphabet, but flying to KUL first leaves no ticket to go on with.
The Idea
Imagine finding a traveller's used plane tickets in a shoebox, all shuffled. Each one says where a flight left from and where it landed. You know the trip began at JFK, and you want to lay the tickets out again in the order they were flown.
In Example 1 that is easy. Only one ticket leaves JFK, and it goes to MUC. Only one leaves MUC, to LHR, then one to SFO, then one to SJC. Following the tickets one by one gives JFK, MUC, LHR, SFO, SJC.
Example 2 offers choices. JFK has tickets to both SFO and ATL, so which comes first? The problem settles it with lexical order: compare two possible trips like words in a dictionary, at the first airport where they differ, and keep the one whose name comes first in the alphabet. ATL comes before SFO, so the trip flies to ATL first.
So should we always take the ticket with the smallest destination? A rule like that, which only looks at the next step, is called a greedy choice. Example 3 shows that it is not enough on its own. From JFK, KUL comes before NRT, but nobody ever leaves KUL. After flying there, the tickets from JFK to NRT and from NRT back to JFK are still unused, with no way to reach them. The right trip goes to NRT, back to JFK, and only then to KUL.
Look at the picture below. On the left, each circle is an airport and each arrow is one ticket, pointing the way it was flown. Airports joined by arrows like this form a graph, and a trip that uses every arrow exactly once is called an Eulerian path. Under the graph, each airport is listed with the places it has tickets to: JFK to KUL and NRT, NRT to JFK, and KUL to none.
The orange arrow to KUL is the dead end. Getting stuck there tells us something useful: a place we cannot leave has to be the last stop of the trip. So instead of throwing the greedy walk away, keep it, and write each airport down only when it has no tickets left, adding it to the front of the route.
Follow the right side of the picture. The walk flies to KUL, gets stuck, and line 1 writes down KUL. Back at JFK, the walk takes the next ticket to NRT, then flies back to JFK. That second visit to JFK finds no tickets left, so line 2 puts JFK in front. Then NRT is finished (line 3), and then the first JFK (line 4). The route reads JFK, NRT, JFK, KUL, the expected answer.
The detour through NRT, which the walk skipped at first, slid in front of the dead end on its own. This way of building an Eulerian path is known as Hierholzer's algorithm.
Solution Approach
The code has three decisions to make: how to store the tickets, how to pick and use up the next ticket, and when to write an airport down. Simply trying routes would also work, but slowly.
Trying routes and undoing them
Why not just try? Take the smallest ticket, and if the walk gets stuck with tickets unused, undo the last flight and try the next ticket instead. That finds the answer, but every wrong turn means walking back and trying again, and with many choices the retries multiply. Writing each airport down only once it has no tickets left, as in the picture, never has to undo anything.
Storing the tickets
How do we find the tickets out of an airport quickly? Keep a HashMapfrom
Each entry is a PriorityQueue
PriorityQueue<String> out = new PriorityQueue<>(Comparator.naturalOrder());
Two identical tickets, such as two from JFK to ATL, become two entries in the queue, so both get used.
Using up the next ticket
How do we make sure a ticket is flown only once? poll()
Writing an airport down
When exactly is an airport finished? When its queue is empty, either because all its tickets were used or because it never had any, like KUL or SJC. The walk is written as a method that calls itself, once per flight taken, so finishing a call means that airport is done. At that moment it goes to the front of the route, which a LinkedListaddFirst
Java Solution
The method findItinerary
- First, build the adjacency list: a
namedHashMap from each airport to aflights of its destinations. For each ticketPriorityQueue ,t creates the queue the first time an airport shows up as acomputeIfAbsent , andfrom puts the destination in it.add - Create an empty
namedLinkedList , and start the walk withroute .visit("JFK", flights, route) - Inside
,visit is the airport's queue, orout for an airport nobody leaves. Whilenull still has tickets,out takes the smallest destination, andout.poll() calls itself for that airport.visit - When that loop ends, the airport has no tickets left, so
puts it at the front of the route.route.addFirst(airport) - When the first call, for JFK, returns,
holds the whole trip, androute returns it.findItinerary
The maintickets"JFK-MUC"
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
public class ReconstructItinerary {
public static List<String> findItinerary(List<List<String>> tickets) {
Map<String, PriorityQueue<String>> flights = new HashMap<>();
for (List<String> t : tickets) {
flights.computeIfAbsent(t.get(0), k -> new PriorityQueue<>(Comparator.naturalOrder()))
.add(t.get(1));
}
LinkedList<String> route = new LinkedList<>();
visit("JFK", flights, route);
return route;
}
private static void visit(String airport, Map<String, PriorityQueue<String>> flights,
LinkedList<String> route) {
PriorityQueue<String> out = flights.get(airport);
while (out != null && !out.isEmpty()) {
visit(out.poll(), flights, route); // poll() takes the smallest ticket and uses it up
}
route.addFirst(airport); // no tickets left here: write it in front
}
private static List<List<String>> tickets(String... pairs) {
List<List<String>> list = new ArrayList<>();
for (String p : pairs) {
list.add(List.of(p.split("-")));
}
return list;
}
public static void main(String[] args) {
System.out.println(findItinerary(tickets("MUC-LHR", "JFK-MUC", "SFO-SJC", "LHR-SFO")));
System.out.println(findItinerary(
tickets("JFK-SFO", "JFK-ATL", "SFO-ATL", "ATL-JFK", "ATL-SFO")));
System.out.println(findItinerary(tickets("JFK-KUL", "JFK-NRT", "NRT-JFK")));
System.out.println(findItinerary(tickets("JFK-ATL", "ATL-JFK", "JFK-ATL")));
System.out.println(findItinerary(tickets("JFK-LAX")));
}
}
Running it prints:
[JFK, MUC, LHR, SFO, SJC]
[JFK, ATL, JFK, SFO, ATL, SFO]
[JFK, NRT, JFK, KUL]
[JFK, ATL, JFK, ATL]
[JFK, LAX]
The third line, [JFK, NRT, JFK, KUL][JFK, KUL]
In [JFK, ATL, JFK, ATL][JFK, LAX]out != null
Complexity
Each ticket goes into a queue once and comes out once, so the cost is set by the number of tickets, E.
- Time: O(E log E), because each of the E tickets is added to a queue and later polled from it, and each of those queue steps costs at most log E.
- Space: O(E), because the queues hold all E tickets, the route holds E + 1 airports, and the calls of
can be E deep when the trip is one long chain like Example 1.visit
For more on walking a graph by going as deep as possible first, see