Connecting flights
- O(n) · Medium
- Full plan
- Python
- JavaScript
- strings
- lists
- booleans
Problem
Noah booked a trip around South America with several stopovers, and his ticket lists each leg as the code of the city it leaves from and the code of the city it lands in. Before printing it, the travel agent checks that no leg departs from a city he is not in.
Write a function that takes the list of legs, in order, and returns true if every leg leaves from the city where the previous one landed, and false if any does not. Each leg is a string shaped like "MEX-BOG": three capital letters for departure, a hyphen and three letters for arrival, with no spaces.
["MEX-BOG", "BOG-LIM", "LIM-SCL"] is connected: true. In ["MEX-BOG", "LIM-SCL"] he lands in BOG and leaves from LIM: false. Going back to a city he already visited is fine. An empty list, or one with a single leg, is connected.
Examples
The example
["MEX-BOG", "BOG-LIM", "LIM-SCL"] → true
Both land in the same city
["MEX-BOG", "LIM-BOG"] → false
A single leg
["GDL-CUN"] → true
There and back
["MEX-BOG", "BOG-MEX"] → true
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def is_connected(legs):
passJavaScript
function isConnected(legs) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.