A traveller kept a loose pile of one-way plane tickets. Each tickets[i] = [from, to] takes them from airport from to airport to, and every airport is named by a three-letter code. The trip began at "JFK", and it used every ticket exactly once.
Put the trip back together and return it as the list of airports in the order visited, starting with "JFK".
Several orders may use up all the tickets. Return the one that comes first alphabetically: compare two candidate trips airport by airport, and the first airport where they differ decides.
The tickets arrive shuffled, but only one chain starts at JFK and uses all three.
There are two JFK → ATL tickets. Two trips use everything: this one, and ["JFK","BOS","JFK","ATL","JFK","ATL"]. They first differ at the second airport, where ATL comes before BOS. Going to ATL a second time at the third step would leave the BOS tickets unused, so the trip has to visit BOS in between.
AMS comes before CDG, but no ticket leaves AMS: flying there first would strand the round trip to CDG. So AMS has to be the last stop.
Constraints
1 <= tickets.length <= 300tickets[i].length == 2from and to are each exactly three upper-case English letters.from != to"JFK" uses every ticket exactly once.Each ticket is a one-way edge, and the trip uses every edge exactly once, starting at JFK. Always taking the alphabetically smallest ticket is almost right; the catch is a dead end taken too early.
Draw each airport as a dot and each ticket as a one-way arrow. The trip is a walk that starts at JFK and travels along every arrow exactly once. Among all such walks, you want the one that reads first alphabetically, which suggests a greedy rule: at each airport, take the ticket to the alphabetically smallest destination.
Time O(m log m)Space O(m)
The full walkthrough and code are part of Premium