Skip to the code
cf.
+50 XP

#480 Rebuild the Trip From Tickets

hard

A travel app imports a pile of used tickets, each [from, to] with place codes as strings, and must rebuild the whole trip. The trip starts at start and uses every ticket exactly once, in some order where each ticket starts where the previous one ended.

Write rebuildTrip(tickets, start) that returns the list of places visited, in order. If several trips are possible, return the one that comes first when comparing the lists place by place in plain string order. At least one valid trip always exists.

Example 1

Input: tickets = [["HOME","LON"],["LON","PAR"],["PAR","HOME"],["HOME","ROM"]], start = "HOME"
Output: ["HOME","LON","PAR","HOME","ROM"]

Going to ROM first would leave the other three tickets unused, since nothing leaves ROM. So the loop through LON and PAR comes first.

Example 2

Input: tickets = [["A","B"],["A","C"],["C","A"]], start = "A"
Output: ["A","C","A","B"]

B comes before C alphabetically, but going to B first gets stuck with tickets left.

Constraints

  • 1 <= tickets.length <= 300
  • Place codes are 1 to 5 uppercase letters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).