Reconstruct Itinerary

Difficulty: Hard

You're given one traveler's airline tickets, each a pair [from, to] of three-letter airport codes. The trip starts at "JFK" and uses every ticket exactly once.

Return the itinerary as a list of airport codes, in visiting order. If several itineraries work, return the one that comes first alphabetically, compared stop by stop (visiting "ATL" beats visiting "SFO" at the same stop). The input always has at least one valid itinerary.

Examples

Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
Output: ["JFK","MUC","LHR","SFO","SJC"]

There's only one way to use every ticket starting from JFK.

Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]

Two different itineraries use every ticket exactly once - this one, and ["JFK","SFO","ATL","JFK","ATL","SFO"]. Comparing them stop by stop, the second stop is "ATL" vs "SFO", and "ATL" is alphabetically smaller, so the itinerary starting "JFK","ATL",... is preferred.

Constraints

  • 1 <= tickets.length <= 300

  • tickets[i].length == 2

  • All airport codes are three uppercase English letters.

  • You may assume every itinerary uses all the tickets and forms at least one valid route.

Approach

Each ticket is a directed edge, and using every ticket once means walking every edge once - the classic Eulerian path problem. The input guarantees such a path exists from "JFK".

A naive greedy DFS (always fly to the smallest airport) aims for the lexically smallest route, but can dead-end early: a ticket might strand you where unused tickets are out of reach.

Hierholzer's algorithm fixes this. Run the same greedy DFS, but record an airport only after all its outgoing tickets are used, and prepend it to the result. A dead end is recorded right away. The airport that led into it still has tickets to try; those are explored and prepended afterward, so in the final order they come before the dead-end branch, which ends up last. Tracing a few small examples by hand makes this "record on exit, prepend" trick click.

Solutions

Brute Force - Try Every Ticket Order

With at most a few hundred tickets, a naive approach picks tickets one at a time. At each airport, try every unused ticket leaving it, in alphabetical order of destination (so the first complete route found is the lexically smallest). Recurse, and backtrack if a choice dead-ends before every ticket is used. It returns as soon as one complete route is found.

function findItinerary(tickets) {
  const routesFrom = new Map();
  for (const [from, to] of tickets) {
    if (!routesFrom.has(from)) routesFrom.set(from, []);
    routesFrom.get(from).push(to);
  }
  for (const destinations of routesFrom.values()) {
    destinations.sort();
  }

  const used = new Array(tickets.length).fill(false);
  const route = ["JFK"];

  function backtrack(current) {
    if (route.length === tickets.length + 1) return true;

    const destinations = routesFrom.get(current) || [];
    for (let i = 0; i < destinations.length; i++) {
      // Find some unused ticket from "current" to destinations[i] - this
      // re-scans the whole ticket list on every step, which is what
      // makes this the brute force version rather than the optimal one.
      let ticketIndex = -1;
      for (let j = 0; j < tickets.length; j++) {
        if (tickets[j][0] === current && tickets[j][1] === destinations[i] && !used[j]) {
          ticketIndex = j;
          break;
        }
      }
      if (ticketIndex === -1) continue;

      used[ticketIndex] = true;
      route.push(destinations[i]);

      if (backtrack(destinations[i])) return true;

      route.pop();
      used[ticketIndex] = false;
    }
    return false;
  }

  backtrack("JFK");
  return route;
}

Time: O(E^2) in the worst case, where E is the number of tickets, since each of the E steps may re-scan the ticket list · Space: O(E) for the recursion stack, the route, and the used-ticket tracking

Optimal - Hierholzer's Algorithm

Group tickets by departure airport and sort each airport's destinations so the smallest is tried first. Run a DFS that, at each airport, removes and follows the smallest remaining destination until none are left.

The key trick: push an airport onto the result only when its DFS call is about to return (all its outgoing tickets are used). A dead end is pushed immediately, while the airport that led into it explores its remaining tickets and is pushed later - so after reversing, it appears before the dead-end branch. Reversing the final list gives the route in forward order.

function findItinerary(tickets) {
  const routesFrom = new Map();
  for (const [from, to] of tickets) {
    if (!routesFrom.has(from)) routesFrom.set(from, []);
    routesFrom.get(from).push(to);
  }
  for (const destinations of routesFrom.values()) {
    // Sort descending so the alphabetically smallest destination can
    // be removed cheaply from the end of the array.
    destinations.sort().reverse();
  }

  const route = [];

  function visit(airport) {
    const destinations = routesFrom.get(airport);
    while (destinations && destinations.length > 0) {
      const next = destinations.pop();
      visit(next);
    }
    route.push(airport);
  }

  visit("JFK");
  return route.reverse();
}

Time: O(E log E) for sorting each airport's destination list, then O(E) for the traversal itself, where E is the number of tickets · Space: O(E) to store the routes-by-airport map and the recursion stack