Algo-Sim › Advanced Graphs

Reconstruct Itinerary

Hard · Advanced Graphs · step through it in Java, Python and C++ on your own input

Use every ticket exactly once, starting from JFK: Hierholzer’s algorithm for an Eulerian path, taking the smallest destination first.

Problem

Given airline tickets where tickets[i] = [from, to], reconstruct the itinerary in order. It must start at "JFK" and use every ticket exactly once. If several itineraries work, return the one that is smallest in lexical order when read as a single string.

Constraints

Edge cases to test

Follow-up questions

Why does Hierholzer’s algorithm add airports in post-order?
A dead end can only be the end of the trip; adding it when stuck and reversing at the end puts it last.
What is the cost?
O(E log E) for sorting the destinations, then O(E) for the walk.

Solution

Java

public List<String> findItinerary(List<List<String>> tickets) {
    Map<String, PriorityQueue<String>> graph = new HashMap<>();
    for (List<String> t : tickets) {
        graph.computeIfAbsent(t.get(0), k -> new PriorityQueue<>()).add(t.get(1));
    }
    LinkedList<String> route = new LinkedList<>();
    Deque<String> stack = new ArrayDeque<>();
    stack.push("JFK");
    while (!stack.isEmpty()) {
        PriorityQueue<String> next = graph.get(stack.peek());
        if (next != null && !next.isEmpty()) {
            stack.push(next.poll());
        } else {
            route.addFirst(stack.pop());
        }
    }
    return route;
}

Python

from collections import defaultdict


def find_itinerary(tickets):
    graph = defaultdict(list)
    # Sorted backwards, so pop() hands out the smallest destination first.
    for src, dst in sorted(tickets, reverse=True):
        graph[src].append(dst)
    stack, route = ["JFK"], []
    while stack:
        if graph[stack[-1]]:
            stack.append(graph[stack[-1]].pop())
        else:
            route.append(stack.pop())
    return route[::-1]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<string> findItinerary(vector<vector<string>> &tickets) {
        unordered_map<string, priority_queue<string, vector<string>, greater<string>>> graph = {};
        for (vector<string> &t : tickets) {
            graph[t[0]].push(t[1]);
        }
        deque<string> route = {};
        deque<string> stack = {};
        stack.push_back("JFK");
        while (!stack.empty()) {
            auto &next = graph[stack.back()];
            if (!next.empty()) {
                stack.push_back(next.top());
                next.pop();
            } else {
                route.push_front(stack.back());
                stack.pop_back();
            }
        }
        return vector<string>(route.begin(), route.end());
    }
};

More Advanced Graphs problems