Junior — Senior
Ticket route sorting function
livecode
Task condition
Given an array tickets containing a set of unrelated tickets. Each ticket is an object with fields from (departure city) and to (destination city). You need to write a function sortTickets(tickets) that rearranges the array elements so that it forms a sequence of the traveler’s journey from the starting city to the final destination.
Task conditions:
- It is guaranteed that all tickets form one continuous path without loops.
- The algorithm must run in linear time O(N).
- There are no restrictions on additional memory.
The result of the function should be an array of tickets sorted in the order of the route.
const tickets = [
{ from: 'Kaliningrad', to: 'Chelyabinsk' },
{ from: 'Moscow', to: 'Kaliningrad' },
{ from: 'Pyatigorsk', to: 'Krasnodar' },
{ from: 'Chelyabinsk', to: 'Astana' },
{ from: 'Krasnodar', to: 'Moscow' },
];