You are given a stack of travel tickets for various transportations that will take you from a point A to point B via several stops on the way. All of the tickets are out of order and you don't know where your journey starts, nor where it ends. Sort the tickets in the right order to complete your journey.
tickets = [ {from: "Barcelona", to: "New York"} {from: "Barcelona", to: "Gerona"}, {from: "Madrid", to: "Barcelona"}, {from: "Gerona", to: "Barcelona"} ]
I suppose, the right order is that one:
tickets = [ {from: "Madrid", to: "Barcelona"}, {from: "Barcelona", to: "Gerona"}, {from: "Gerona", to: "Barcelona"}, {from: "Barcelona", to: "New York"} ]
Because there is no ticket to Madrid, and no ticket from New York.
What would be the best algorithm for that task?
The language is JavaScript, but language-agnostic solution would be good enough.
Update: I changed sample data to be not confused with One-way flight trip problem.