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], return the trip they make. All the tickets belong to one traveller who started at "JFK", and the trip must use every ticket exactly once. If several trips are possible, return the one that is smallest in lexical order, comparing the trips airport by airport like words in a dictionary. At least one valid trip always exists.

Example 1
Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
Output: ["JFK","MUC","LHR","SFO","SJC"]
Example 2
Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Example 3
Input: tickets = [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]
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.
Solution

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.

Example 3 as a graph: JFK has tickets to KUL and NRT, NRT has a ticket back to JFK, and KUL is a dead end. The route is built from the back: KUL, then JFK, then NRT, then the first JFK, giving JFK, NRT, JFK, KUL.

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 HashMap from each airport to the places it has tickets to, exactly the list under the graph in the picture. A list like that, one entry per airport with its neighbours, is called an adjacency list. Each ticket adds one destination to the entry for its from airport.

Each entry is a PriorityQueue, set up as a min-heap: whatever order the destinations go in, the smallest comes out first. In Example 2, SFO goes into the queue for JFK before ATL, yet ATL comes out first. Airport names are strings, and their natural order is alphabetical:

Java
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() returns the smallest destination and removes it from the queue in the same step. The ticket is gone before the walk moves on, so no later visit to that airport can take it again.

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 LinkedList does in constant time with addFirst.

Java Solution

The method findItinerary works in these steps:

  1. First, build the adjacency list: a HashMap named flights from each airport to a PriorityQueue of its destinations. For each ticket t, computeIfAbsent creates the queue the first time an airport shows up as a from, and add puts the destination in it.
  2. Create an empty LinkedList named route, and start the walk with visit("JFK", flights, route).
  3. Inside visit, out is the airport's queue, or null for an airport nobody leaves. While out still has tickets, out.poll() takes the smallest destination, and visit calls itself for that airport.
  4. When that loop ends, the airport has no tickets left, so route.addFirst(airport) puts it at the front of the route.
  5. When the first call, for JFK, returns, route holds the whole trip, and findItinerary returns it.

The main method runs the three examples, two identical tickets from JFK to ATL, and a trip of a single ticket. A small helper, tickets, turns text such as "JFK-MUC" into a ticket.

Java
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:

Output
[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], is Example 3: KUL was reached first but written down first too, so it ends up at the back. Writing each airport down on arrival instead, with the same smallest-first choice, gives [JFK, KUL] and stops, with the tickets JFK to NRT and NRT to JFK still unused.

In [JFK, ATL, JFK, ATL] both tickets from JFK to ATL were flown, because each one is its own entry in the queue. The last line, [JFK, LAX], shows that LAX, which has no queue at all, is handled by the out != null check.

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 visit can be E deep when the trip is one long chain like Example 1.

For more on walking a graph by going as deep as possible first, see Depth First Search.