InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Advanced Graphs

Reconstruct Itinerary

hard Original ↗ 00:00

Problem

You are given a list of airline tickets where each tickets[i] = [from, to] is 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 as separate flights.

If more than one complete itinerary exists, return the one that is smallest in lexical order when the airport codes are read 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 form a single chain.
  • tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]["JFK","ATL","JFK","SFO","ATL","SFO"] — starting ["JFK","SFO",...] also uses all tickets, but starting with ATL is lexically smaller.
  • tickets = [["JFK","AAA"],["AAA","JFK"],["JFK","BBB"]]["JFK","AAA","JFK","BBB"] — flying to AAA first is valid because the return ticket brings you back to JFK.

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 is an Eulerian path, not a Hamiltonian one, and Eulerian paths can be found 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 algorithm: 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, with no backtracking to undo.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug