Reconstruct Itinerary - Problem

You are given a list of airline tickets where tickets[i] = [from_i, to_i] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.

All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.

For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].

You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.

Input & Output

Example 1 — Basic Circuit
$ Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
Output: ["JFK","MUC","LHR","SFO","SJC"]
💡 Note: Start from JFK, follow tickets: JFK → MUC → LHR → SFO → SJC. This uses all tickets exactly once.
Example 2 — Multiple Valid Paths
$ Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
💡 Note: Multiple valid itineraries exist, but we return the lexicographically smallest one.
Example 3 — Simple Round Trip
$ Input: tickets = [["JFK","KUL"],["KUL","JFK"]]
Output: ["JFK","KUL","JFK"]
💡 Note: Simple round trip: JFK → KUL → JFK using both tickets.

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

Visualization

Tap to expand
Reconstruct Itinerary INPUT Flight Tickets Graph JFK MUC LHR SFO SJC [["MUC","LHR"],["JFK","MUC"], ["SFO","SJC"],["LHR","SFO"]] ALGORITHM STEPS Hierholzer's Algorithm 1 Build Adjacency List Sort destinations lexically JFK: [MUC] MUC: [LHR] LHR: [SFO] SFO: [SJC] 2 DFS from JFK Visit smallest dest first 3 Remove Used Edges Pop from adjacency list 4 Post-order Insert Add to result after DFS DFS Call Stack: visit(JFK) --> visit(MUC) --> visit(LHR) --> visit(SFO) --> visit(SJC) --> return Result builds in reverse! FINAL RESULT Complete Itinerary JFK MUC LHR SFO SJC Start End ["JFK","MUC","LHR","SFO","SJC"] OK Key Insight: Hierholzer's algorithm finds an Eulerian path by using DFS with post-order insertion. Sorting adjacency lists lexically ensures smallest lexical order. Build result in reverse by adding nodes after all their edges are visited. Time: O(E log E), Space: O(E). TutorialsPoint - Reconstruct Itinerary | Hierholzer's Algorithm (Eulerian Path)
Asked in
Google 42 Amazon 35 Facebook 28 Microsoft 24
168.5K Views
Medium-High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen