15% off all plans & roadmaps Use code

See plans

Reconstruct Itinerary

Updated

TL;DR: Use every flight ticket exactly once, starting at JFK, and return the lexicographically smallest route. Hierholzer's algorithm with a stack and sorted destinations finds it in O(E log E).

Problem

You get a list of airline tickets, where tickets[i] = [from, to] is one directed flight from airport from to airport to. An itinerary is a sequence of airports in which each consecutive pair matches a ticket.

Build an itinerary that starts at "JFK" and uses every ticket exactly once. Duplicate tickets are separate flights, so each copy must be used on its own.

A valid itinerary is guaranteed to exist. If several valid itineraries exist, return the one that is smallest in lexicographical order when you compare the airport sequences from left to right.

Example 1

Input: tickets = [["JFK","BOS"],["BOS","DEN"],["DEN","JFK"],["JFK","LIM"],["LIM","BOS"]]
Output: ["JFK","BOS","DEN","JFK","LIM","BOS"]
Explanation: From JFK you take the BOS ticket before the LIM ticket to get the smallest second airport. The route then goes BOS to DEN, DEN to JFK, JFK to LIM, and LIM to BOS, which uses all five tickets.

Example 2

Input: tickets = [["JFK","AMS"],["JFK","BER"],["AMS","BER"],["BER","JFK"]]
Output: ["JFK","AMS","BER","JFK","BER"]
Explanation: AMS is smaller than BER, so the route starts JFK to AMS. The remaining tickets then force AMS to BER, BER to JFK, and JFK to BER.

Example 3

Input: tickets = [["JFK","OSL"],["OSL","JFK"],["JFK","RIX"],["RIX","JFK"],["JFK","OSL"]]
Output: ["JFK","OSL","JFK","RIX","JFK","OSL"]
Explanation: The route takes JFK to OSL and back to JFK. Taking the second JFK to OSL ticket at that point would strand you at OSL with tickets left, so the route must go to RIX first and finish with the last JFK to OSL ticket.

Constraints

  • 1 <= tickets.length <= 300
  • tickets[i].length == 2
  • Every airport code is exactly 3 uppercase English letters.
  • The itinerary must start at "JFK".
  • At least one valid itinerary uses every ticket exactly once.

Constraints that matter

  • tickets.length is at most 300, so an O(E log E) graph solution is trivial, but trying every ticket order (up to 300 factorial) is hopeless in the worst case.
  • A valid itinerary is guaranteed, so you never need to detect failure. This is what lets Hierholzer's algorithm skip any feasibility check.
  • Duplicate tickets are allowed, so you must store destinations in a multiset (a heap or a sorted list), never a set.
  • Airport codes are fixed-length uppercase strings, so plain string comparison gives the required lexicographic order in every language.
  • The route has E + 1 airports and recursion can reach depth E, which is 300 here. That is safe in Python, but an explicit stack removes the worry.

View on LeetCode

Hints

Hint 1

Each ticket is a directed edge, and you must use every edge exactly once.

Hint 2

Sort the tickets so that, for each airport, destinations come in alphabetical order.

Solution

Intuition

Each ticket is a directed edge, and you must use every edge exactly once. That is an Eulerian path problem. The route is a walk that crosses every edge one time, starting at JFK.

Picture a hiker walking trails and writing a junction in the notebook only after every trail leaving it is used up. The stack is the hiker's current path, and the notebook is the route list, so reversing the notebook gives the walk.

The lexicographic rule tempts you to be greedy: always take the smallest destination. Example 3 shows why that fails. From JFK the smallest ticket leads to OSL, then back to JFK, and a second OSL ticket leads to a dead end because OSL has no outgoing tickets left. The greedy walk gets stuck with the RIX tickets unused.

The fix is to notice that the dead-end airport must be the last stop of the route. So you still walk greedily, but you only write an airport into the answer when it has no outgoing tickets left. Dead ends get written first, and the cycles you skipped are spliced in before them as the stack unwinds. Reverse the written order and you have the itinerary.

This is a stack pattern. The explicit stack holds the current partial walk. When the top airport has an unused ticket, you push its smallest destination. When it has none, you pop it into the answer.

Because you always try the smallest destination first, the first complete walk this process finishes is the smallest one.

Watch the pattern animation

Worked example

Input: tickets = [["JFK","JFK"]]
Output: ["JFK","JFK"]
Explanation: There is one ticket, a flight from JFK back to JFK. The route starts at JFK, takes that ticket, and lands at JFK again, so the answer has two airports: one more than the number of tickets.
Simulation / Backtracking Helper pattern infographic for Reconstruct Itinerary

Solution pattern

Simulation / Backtracking Helper

Part of Stack Patterns

Approach 1: Brute force: sorted backtrackingSimulation / Backtracking Helper

Sort the tickets so that, for each airport, destinations come in alphabetical order. Then run a depth-first search over ticket choices. At each airport, try each unused ticket in sorted order, mark it used, recurse, and undo the mark if the branch fails.

Because tickets are tried in sorted order, the first complete itinerary the search finds is the lexicographically smallest. You can stop at the first success. To avoid repeating identical work, skip a ticket that equals the previous ticket when that previous copy is unused, since trying it would repeat the same branch.

Steps

  1. Copy the tickets and sort them by departure, then by destination.
  2. Create a used array of E booleans and a path list that starts with JFK.
  3. Define dfs: if path has E + 1 airports, return true.
  4. Scan all tickets. Skip a ticket if it is used, departs from a different airport than the last path airport, or duplicates the previous unused ticket.
  5. Mark the ticket used, append its destination, and call dfs. If it returns true, return true.
  6. Otherwise remove the destination and unmark the ticket, then try the next ticket.
  7. Return false when no ticket works, and return path after the top-level call.

Dry run

Take [["JFK","JFK"]]. After sorting, there is one ticket. path = [JFK] and used = [false].

dfs sees path length 1, which is not E + 1 = 2. It scans ticket 0: unused and departs from JFK, which matches the last path airport. It marks the ticket used and appends JFK, so path = [JFK, JFK].

The recursive call sees path length 2 = E + 1 and returns true. The top call returns true and the answer is [JFK, JFK].

Complexity

TimeO(E!) in the worst case
SpaceO(E)

Let E be the number of tickets. Each recursion level scans all E tickets, and in the worst case the search can try every ordering of the tickets, so the number of explored orders is bounded by E factorial. Real inputs prune hard, but dead ends deep in the search can still force heavy backtracking. Space is O(E) for the used array, the path, and a recursion depth of at most E.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        ts = sorted(tickets)
        n = len(ts)
        used = [False] * n
        path = ["JFK"]

        def dfs() -> bool:
            if len(path) == n + 1:
                return True
            cur = path[-1]
            for i in range(n):
                if used[i] or ts[i][0] != cur:
                    continue
                # same flight as the previous copy, which was already tried
                if i > 0 and ts[i] == ts[i - 1] and not used[i - 1]:
                    continue
                used[i] = True
                path.append(ts[i][1])
                if dfs():
                    return True
                path.pop()
                used[i] = False
            return False

        dfs()
        return path

Approach 2: Hierholzer's algorithm with a stackOptimal

What's slow: backtracking guesses a ticket, walks far down the branch, discovers a dead end, and undoes work. The same suffixes get rebuilt again and again, and the scan over all E tickets at each step adds more cost.

The insight that fixes it: a dead-end airport can only be the end of the route, so you never need to undo it. Walk greedily with the smallest destination, and write an airport into the answer only when it has no unused tickets. The airports come out in reverse order, so reverse them at the end. Each ticket is consumed once and never put back.

Store each airport's destinations so the smallest one is cheap to remove: a min-heap, or a list sorted in descending order so that pop() from the end gives the smallest. Use an explicit stack so recursion depth is never a concern.

Why it is correct. The first airport the walk gets stuck at must be the final stop, since nothing leaves it. Every other airport is written only after all its departures are used, so each detour is spliced in before the point where it branched off. Reversing the written order therefore uses every ticket once, and taking the smallest destination first keeps the result lexicographically smallest.

Steps

  1. Build a map from each departure airport to its destinations, kept so the smallest is removed first (a min-heap or a descending sorted list).
  2. Push JFK onto the stack and create an empty route list.
  3. While the stack is not empty, look at the top airport.
  4. If the top airport has an unused ticket, remove its smallest destination and push it onto the stack.
  5. Otherwise, pop the top airport and append it to route.
  6. When the stack is empty, reverse route and return it.

Dry run

StepStack (top on right)Tickets left at JFKActionroute
0[JFK][JFK]start[]
1[JFK, JFK][]top JFK has a ticket, remove JFK and push it[]
2[JFK][]top JFK has no tickets, pop and record[JFK]
3[][]top JFK has no tickets, pop and record[JFK, JFK]

The stack is empty, so reverse route = [JFK, JFK]. Both entries are the same, so the reversed list is [JFK, JFK], which matches the expected output.

A second check on Example 3 shows the dead end. The walk goes JFK, OSL, JFK, OSL, and the last OSL has no tickets, so OSL is recorded first. Popping back to JFK finds the RIX ticket, which pushes RIX and JFK. After those pop, the route is recorded as OSL, JFK, RIX, JFK, OSL, JFK, and reversing it gives the expected answer.

Complexity

TimeO(E log E)
SpaceO(E)

Let E be the number of tickets. Building the structure costs O(E log E) for heap inserts or sorting. Each ticket is removed exactly once, and each removal costs at most O(log E) with a heap. The loop runs 2E + 1 iterations in total: one push per ticket plus one pop per stack entry. Space is O(E) because the map holds E destinations, and the stack and route each hold at most E + 1 airports.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        graph = {}
        # descending order, so pop() from the end gives the smallest destination
        for src, dst in sorted(tickets, reverse=True):
            graph.setdefault(src, []).append(dst)

        stack = ["JFK"]
        route = []
        while stack:
            top = stack[-1]
            if graph.get(top):
                stack.append(graph[top].pop())
            else:
                route.append(stack.pop())
        return route[::-1]

Common mistakes

  • Using a plain greedy walk, route.append(next) as soon as you pick the smallest destination. Example 3 breaks it because the walk dead-ends at OSL. Record an airport only when it has no tickets left, then reverse.
  • Storing destinations in a set. Duplicate tickets such as two JFK to OSL flights collapse into one, so the route comes up short. Use a heap, a list, or a multiset.
  • Forgetting the final reverse. The stack pops airports from the end of the trip to the start, so returning route as is gives the itinerary backward.
  • Popping the largest destination from a list sorted in ascending order. If you pop from the end, sort descending. If you pop from the front, sort ascending and accept an O(n) removal, or use a heap.
  • In the backtracking version, not restoring state on failure: used[i] = true without used[i] = false, or path.append without path.pop. Later branches then see tickets as spent and the search returns a wrong or empty path.
  • Returning the first complete walk from unsorted tickets in backtracking. The first success is only the smallest if you try tickets in sorted order, so sort first.

Edge cases

  • One ticket [["JFK","JFK"]] returns ["JFK","JFK"], a self-loop used once.
  • A single ticket [["JFK","ABC"]] returns ["JFK","ABC"].
  • Duplicate tickets such as two JFK to OSL flights must both be used, so OSL appears twice in the route.
  • A dead-end airport reachable from JFK, as in Example 3, must be visited last even though it is alphabetically small.
  • A long chain of 300 tickets such as JFK to AAA to BBB and so on produces a 301-airport route. An explicit stack handles it with no recursion limit.
  • An airport that never departs (no entry in the map) must not crash the lookup. Use get with a default or check for a missing key.

Follow-ups interviewers ask

Why does reversing the postorder give the right route?
An airport is recorded only when it has no tickets left, so the first airport recorded is the end of the whole trip. Each later record is the airport that precedes it in some valid ordering of the edges. Reading the records backward therefore gives the walk from start to finish. Taking the smallest destination first means the earliest choices in that walk are the smallest possible.
What changes if no valid itinerary is guaranteed?
Check feasibility first. After the algorithm, verify that the route has E + 1 airports and starts at the required start. If it is shorter, some tickets were unreachable and no Eulerian path exists. You can also check degree conditions up front: at most one airport with out minus in equal to 1, one with in minus out equal to 1, and all others balanced.
Can you do it recursively, and what is the risk?
Yes. Define visit(airport) to pop smallest destinations and recurse until none remain, then append the airport, and reverse at the end. The depth is at most E, which is 300 here, so it fits in default limits. For much larger inputs, the explicit stack avoids a stack overflow.

Reconstruct Itinerary FAQ

What is the time complexity of Reconstruct Itinerary?

The stack-based Hierholzer solution runs in O(E log E), where E is the number of tickets. Sorting or heap inserts cost O(E log E), and each ticket is removed once. The sorted backtracking approach is exponential in the worst case.

Why use Hierholzer's algorithm for Reconstruct Itinerary?

The tickets form a directed graph and you need a path that uses every edge exactly once, which is an Eulerian path. Hierholzer's algorithm builds one in linear steps by recording airports when they run out of tickets. It handles dead ends and cycles without backtracking.

Why does the greedy smallest-first walk fail without postorder recording?

Taking the smallest destination can lead into an airport with no outgoing tickets while other tickets remain, as in Example 3. Writing airports to the answer as you visit them would lock in that bad ordering. Recording them on exit lets the dead end sit at the end and splices the other tickets in before it.

Can Reconstruct Itinerary be solved in O(1) extra space?

No. You need to remember which tickets are unused, and that takes O(E) space. The route itself has E + 1 airports, so the output alone is that large.

How do I write Reconstruct Itinerary in Python or Java?

In Python, sort the tickets in reverse, append each destination to a list per source, and pop from the end while using a list as the stack. In Java, use a HashMap of PriorityQueue<String> and an ArrayDeque as the stack. Both versions are above and follow the same steps.

Is LeetCode 332 solvable with plain backtracking?

Yes, with sorted tickets and a used array, and it returns the correct answer on valid inputs. The worst case is exponential, so Hierholzer is the safe choice for an interview. Mention the backtracking first, then explain why you replace it.

Asked at

See which companies ask this — Pro

Practise it