Destination City

Tokyo city all bright Photo by Pawel Nolbert

This post is part of the Algorithms Problem Solving series.

Problem description

This is the Destination City problem. The description looks like this:

You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBiReturn the destination city, that is, the city without any path outgoing to another city.

It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.


Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
Output: "Sao Paulo"

Input: paths = [["B","C"],["D","B"],["C","A"]]
Output: "A"

Input: paths = [["A","Z"]]
Output: "Z"


My first approach is to get all the origins and destinations in different lists and the get the first difference between the lists.

def dest_city(paths):
    all_origins = []
    all_destinations = []

    for [city1, city2] in paths:

    return [d for d in all_destinations if d not in all_origins][0]

We can also use the set data structure to use the difference operation:

def dest_city(paths):
    all_origins = set()
    all_destinations = set()

    for [city1, city2] in paths:

    return (all_destinations - all_origins).pop()


Patreon Become a Patron Coffee icon Buy me a coffee