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
- Store each airport's destinations in a min-heap or a reverse-sorted list.
- DFS: while the current airport has unused tickets, take the smallest and recurse.
- 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.