LeetCode #332 Hard

Reconstruct Itinerary

Reconstruct Itinerary is LeetCode 332 (Hard). Each ticket [from, to] is one flight. Starting at "JFK", put the flights in order as one trip that uses every ticket exactly once.

  • At least one valid trip is guaranteed.
  • If several trips work, return the one that is smallest in dictionary order, read as a list of airports.
  • The same ticket can appear more than once, and each copy must be used.
Constraints
  • 1 <= tickets.length <= 300
  • tickets[i].length == 2
  • fromi.length == 3
  • toi.length == 3
  • fromi and toi consist of uppercase English letters.
  • fromi != toi
grapheulerian-pathdfs
Open on LeetCode ↗
02

Intuition

Airports are nodes and tickets are directed edges, so the trip is an Eulerian path: a walk that uses every edge once. Hierholzer's algorithm finds one by walking until it gets stuck and adding each airport to the route only when it has no tickets left.

  • Why stuck means last: at every airport except the final stop, tickets in and tickets out balance, so arriving always leaves a way out. The first dead end is the real end of the trip.
  • Detours fit in: tickets skipped on the way are used when the search backs up, and their airports land in front of the dead end.
  • Smallest order: always fly the alphabetically smallest unused ticket.
How to spot this pattern

"Use every edge exactly once" is an Eulerian path. Hierholzer's algorithm (DFS that records a node after its edges run out, then reverses) builds it in one pass.

03

Approach

Try it first

Before reading on, try the rule "always fly to the smallest destination" on JFK→KUL, JFK→NRT, NRT→JFK. Then decide what to do with an airport that has no tickets left while others are still unused. Aim for O(E log E).

1

Sort each airport's destinations

Sort the tickets in reverse and append each destination to graph[src]. Every list then ends with its smallest destination, so pop() takes the smallest one in O(1) and removes that ticket at the same time.

2

Fly until stuck

In visit(airport), keep popping the smallest destination and calling visit on it. The ticket is removed before the call, so no ticket can ever be used twice.

3

Add an airport once its tickets run out

When graph[airport] is empty, append the airport to route. Airports are added from the end of the trip backwards: the dead end first, then each airport that led to it.

4

Reverse the route

visit("JFK") returns last, so JFK is appended last. route[::-1] therefore starts at JFK and lists the trip in flying order.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findItinerary(self, tickets: List[List[str]]) -> List[str]:
▶3 graph = defaultdict(list)
▶4 for src, dst in sorted(tickets, reverse=True):
▶5 graph[src].append(dst)
▶6 route = []
▶7 
▶8 def visit(airport):
▶9 while graph[airport]:
▶10 visit(graph[airport].pop())
▶11 route.append(airport)
▶12 
▶13 visit("JFK")
▶14 return route[::-1]
JFKKULNRTcall stackroute, built from the endnothing added yetitineraryreversed route goes here3 tickets, smallest destination first
JFKKUL, NRTtickets out
NRTJFKtickets out
Each ticket is an arrow from one airport to another, and the itinerary must use every arrow exactly once. Each airport's destinations are kept in alphabetical order, so the smallest one can always be taken first.
JFKKULNRTcall stackJFKroute, built from the endnothing added yetitineraryreversed route goes herefly JFK to KUL, its smallest unused ticket
atJFK
takeKUL
still left at JFKNRT
From JFK the unused tickets go to KUL, NRT. Take the alphabetically smallest, KUL, cross the ticket off and continue from there. Choosing the smallest first is what makes the final route the smallest in dictionary order.
JFKKULNRTcall stackJFKKULroute, built from the endKULitineraryreversed route goes hereKUL has no tickets left → add it to the route
atKUL
routeKULfrom the end
unused tickets2
KUL has no unused tickets, so nothing more can follow it right now. The first dead end can only be the last stop of the trip: at any other airport, tickets in and out balance, so arriving always leaves a ticket out. It goes at the end of the route.
JFKKULNRTcall stackJFKroute, built from the endKULitineraryreversed route goes herefly JFK to NRT, its only unused ticket
atJFK
takeNRT
still left at JFKnone
From JFK the only unused ticket goes to NRT. Cross it off and continue from there.
JFKKULNRTcall stackJFKNRTroute, built from the endKULitineraryreversed route goes herefly NRT to JFK, its only unused ticket
atNRT
takeJFK
still left at NRTnone
From NRT the only unused ticket goes to JFK. Cross it off and continue from there.
JFKKULNRTcall stackJFKNRTJFKroute, built from the endKULJFKitineraryreversed route goes hereJFK has no tickets left → add it to the route
atJFK
routeKUL, JFKfrom the end
unused tickets0
JFK has no unused tickets, so nothing more can follow it right now. Add it to the route, which lists the trip from its end. Then return to the airport that flew here.
JFKKULNRTcall stackJFKNRTroute, built from the endKULJFKNRTitineraryreversed route goes hereNRT has no tickets left → add it to the route
atNRT
routeKUL, JFK, NRTfrom the end
unused tickets0
NRT has no unused tickets, so nothing more can follow it right now. Add it to the route, which lists the trip from its end. Then return to the airport that flew here.
JFKKULNRTcall stackJFKroute, built from the endKULJFKNRTJFKitineraryreversed route goes hereJFK has no tickets left → add it to the route
atJFK
routeKUL, JFK, NRT, JFKfrom the end
unused tickets0
JFK has no unused tickets, so nothing more can follow it right now. This is the first call, from JFK, so the route is complete: it holds every airport of the trip, last stop first.
JFKKULNRTcall stackroute, built from the endKULJFKNRTJFKitineraryJFKNRTJFKKULreverse the route → JFK → NRT → JFK → KUL
resultJFK, NRT, JFK, KUL
Airports were added from the end of the trip backwards, so reversing the route gives the itinerary. It starts at JFK, uses all 3 tickets once, and took the smallest choice at every airport.
05

Common pitfalls

Adding the airport before flying on

✗ Wrong
route.append(airport)
while graph[airport]:
    visit(graph[airport].pop())
✓ Right
while graph[airport]:
    visit(graph[airport].pop())
route.append(airport)

That is a plain greedy walk. For [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]] it gives JFK, KUL, NRT, JFK, which needs a KUL → NRT flight nobody has. Adding on the way out gives JFK, NRT, JFK, KUL.

Sorting the wrong way for pop()

✗ Wrong
for src, dst in sorted(tickets):
✓ Right
for src, dst in sorted(tickets, reverse=True):

pop() takes the last item, so ascending lists hand out the largest destination first. On [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] this returns a valid trip starting JFK, SFO, but the answer starts JFK, ATL.

Storing destinations in a set

✗ Wrong
graph[src].add(dst)
✓ Right
graph[src].append(dst)

Two identical tickets collapse into one. For [["JFK","ATL"],["ATL","JFK"],["JFK","ATL"]] the set version returns JFK, ATL, JFK and skips a ticket; the answer is JFK, ATL, JFK, ATL.

06

Edge cases

A single ticket, [["JFK","ATL"]]

ATL is stuck at once and goes on the route, then JFK; reversed, that is ["JFK", "ATL"].

The trip passes through JFK again, e.g. [["JFK","ATL"],["ATL","JFK"],["JFK","SFO"]]

Each visit to JFK pops its own ticket from the same list, so the second visit flies on to SFO. The answer is JFK, ATL, JFK, SFO.

07

Complexity

Time
O(E log E)
Space
O(E)
E is the number of tickets. Sorting them dominates; after that each ticket is popped once. The graph, the route and the recursion depth (up to E + 1 calls) are all O(E).
08

Reconstruct Itinerary FAQ

Why not DFS with backtracking?

Trying destinations in order and putting a ticket back when a branch fails also works, and the first full trip it finds is the answer. But a bad early choice can be retried many times, so the worst case is exponential. Hierholzer's algorithm never puts a ticket back.

Can it be written without recursion?

Yes. Keep a stack that starts with JFK. While the airport on top has tickets, push its smallest destination; when it has none, pop it onto the route. Reverse the route at the end. It is the same algorithm with the call stack made explicit.

When does an Eulerian path exist?

In a directed graph whose edges are all connected, every node needs as many edges in as out, except that the start may have one extra edge out and the end one extra edge in. LeetCode guarantees this for the tickets, so the search never fails.