30 · Advanced Graphs: Euler Paths, Bridges & SCCs

#332 Reconstruct Itinerary

Hardsolve on LeetCode ↗

frequently reported atNetflixUberAmazonGoogleMeta

the problem

In plain words

You get a list of flight tickets; each [from, to] uses 3-letter airport codes. The traveller starts at JFK and must use every ticket exactly once. Return the trip as the list of airports in visiting order. If several trips work, return the one that comes first in dictionary order when you compare the airports one by one. A valid trip always exists.

in tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]

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

Only one order uses all four tickets.

in tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]

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

JFK, SFO, ATL, JFK, ATL, SFO also uses every ticket, but ATL < SFO at the second stop.

  • 1 ≤ tickets.length ≤ 300
  • Each code is 3 uppercase letters, and from ≠ to
  • The same ticket may appear more than once
  • At least one valid trip exists

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #787
      Cheapest Flights Within K Stops
      Mediumin Shortest Paths
    2. #210
      Course Schedule II
      Mediumin Topo Sort
    3. #46
      Permutations
      Mediumin Backtracking