TRT
Sign in
hardAdvancedLeetCode#Hierholzer#Eulerian path

Reconstruct itinerary

Use every flight ticket exactly once, starting from JFK and preferring alphabetical order, with a DFS that adds airports after their tickets run out.

The Runtime Theory Team1 min read
Taught inDepth-first searchPro — members onlyDepth-first search follows one path as far as it can, then backs up and tries the next. It is the natural way to flood a region, explore every possibility, or ask what is reachable, as long as you watch its depth.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

intickets = [[MUC, LHR], [JFK, MUC], [SFO, SJC], [LHR, SFO]]

out[JFK, MUC, LHR, SFO, SJC]

intickets = [[JFK, SFO], [JFK, ATL], [SFO, ATL], [ATL, JFK], [ATL, SFO]]

out[JFK, ATL, JFK, SFO, ATL, SFO]

Given airline tickets as [from, to] pairs, reconstruct the itinerary that starts at JFK and uses every ticket exactly once. If several are valid, return the one that is smallest in lexical order.

Before you code

Using every edge exactly once is an Eulerian path. Greedily taking the alphabetically first ticket can strand you at a dead end before all tickets are used, so the itinerary has to be built in a way that recovers from that.

Hints

  1. Store each airport's destinations in a min-heap or a reverse-sorted list.
  2. DFS: while the current airport has unused tickets, take the smallest and recurse.
  3. Append the airport to the route only when it has no tickets left, then reverse the route at the end. Dead ends end up last, where they belong.

Production & complexity notes

When solving Reconstruct itinerary on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Depth-first search to reinforce the underlying pattern.

What it practices

Using DFS finish order, from Depth-first search.

Not started

Sign in to save your learning progress.

Sign in to save