I was asked to design an algorithm that solves the following problem :
Consider a travel from city A to city B, made of several trips by train through other cities in between. With an access to the unordered list of train tickets from which you can read the cities of departure and arrival of each trip, find A and B.
Unfortunately, I was unable to give an efficient algorithm when I needed to (in pseudo code), but once I got home, I came up with this answer (in JavaScript).
var tickets = [
{from:'Paris', to:'Berlin'},
{from:'London', to:'Paris'},
{from:'Zurich', to:'Milan'},
{from:'Berlin', to:'Zurich'}
];
function getTrip(tickets)
{
var ticket = tickets.shift();
var trip = {from:ticket.from, to:ticket.to};
while(tickets.length > 0)
{
ticket = tickets.shift();
if(ticket.from == trip.to)
{
trip.to = ticket.to;
}
else if(ticket.to == trip.from)
{
trip.from = ticket.from;
}
else
{
tickets.push(ticket);
}
}
return trip;
}
var trip = getTrip(tickets);
console.log('The trip was from %s to %s', trip.from, trip.to);
While this might look like a very simple problem, I am still curious to see if there is a more efficient solution (for both time and space) or simply considerations I completely forgot. This may not need to be in JavaScript (especially if the language gives greater control over some aspects of the problem).