InterviewPrepKit

Home / Coding / Advanced Graphs

Reconstruct Itinerary

hard Original ↗
Solving tips
  • 'Use every ticket exactly once' is an Eulerian path (every edge once), not Hamiltonian (every vertex once); airports may repeat.
  • Use Hierholzer's algorithm: walk greedily to the smallest destination until stuck, then record airports in reverse postorder and reverse at the end; no backtracking.
  • Keep destinations in a per-airport min-heap so greedy always picks the lexically smallest, yielding the smallest itinerary.
  • Treat duplicate tickets as distinct edges (use a list/heap, not a set); target O(E log E) time.

Problem

You hold a pile of plane tickets, each tickets[i] = [from, to] — a one-way flight between two three-letter airport codes. Starting from "JFK", build an itinerary that uses every ticket exactly once (duplicate tickets count separately).

If more than one complete itinerary exists, return the one that is smallest in lexical order when the airport codes are read off as a single sequence. You may assume at least one valid itinerary exists.

In graph terms: tickets are directed edges, and you must find a path from "JFK" that traverses every edge exactly once — an Eulerian path — breaking ties alphabetically.

Examples

  • tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]["JFK","MUC","LHR","SFO","SJC"] — the tickets chain into a single line.
  • tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]["JFK","ATL","JFK","SFO","ATL","SFO"]["JFK","SFO",...] also uses all tickets, but starting with ATL is lexically smaller.
  • tickets = [["JFK","AAA"],["AAA","JFK"],["JFK","BBB"]]["JFK","AAA","JFK","BBB"] — greedily flying to AAA first still works because the return ticket brings you back.

Constraints

  • 1 <= len(tickets) <= 300
  • Airport codes are exactly 3 uppercase letters; every itinerary starts at "JFK".
  • At least one valid itinerary exists.

Think about it first

Hint 1 "Use every ticket exactly once" means every edge exactly once (airports may repeat). That's an Eulerian path, not a Hamiltonian one — and Eulerian paths are findable in linear time.
Hint 2 Pure greedy — always fly to the alphabetically smallest unused destination — can strand you: from JFK with tickets to AAA and BBB where only AAA loops back, choosing BBB first dead-ends. Backtracking fixes this but can blow up.
Hint 3 Hierholzer's trick: walk greedily (smallest destination first) until you get stuck; the stuck airport is the end of the itinerary. Record it, back up, and keep going — building the route in reverse postorder. Each edge is touched once, no backtracking ever undone.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.