SDE & MLE Prep

332. Reconstruct Itinerary

Problem

tickets[i] = [from, to] are airline tickets. Rebuild the itinerary that starts at "JFK" and uses every ticket exactly once. If several exist, return the one that is lexicographically smallest when read as a sequence of airport codes. At least one valid itinerary exists.

Example: [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] → ["JFK","MUC","LHR","SFO","SJC"]

Use every ticket exactly once = Eulerian path. Hierholzer: DFS taking the smallest destination first, append a node after all its edges are used, then reverse. Dead ends get placed at the end automatically.

JFK -> KUL (dead end) and JFK -> NRT -> JFK
DFS JFK: go KUL (smallest) -> stuck -> post-order [KUL]
back at JFK: go NRT -> JFK -> stuck ... -> [KUL, JFK, NRT, JFK]
reverse -> JFK NRT JFK KUL

Complexity: O(E log E).

class Solution:
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        g = defaultdict(list)
        for a, b in sorted(tickets, reverse=True):
            g[a].append(b)               # reverse-sorted so pop() gives smallest
        route, st = [], ["JFK"]
        while st:
            while g[st[-1]]:
                st.append(g[st[-1]].pop())
            route.append(st.pop())
        return route[::-1]