DEV Community

Cover image for Algorithms Problem Solving: Destination City
TK
TK

Posted on • Originally published at leandrotk.github.io

1

Algorithms Problem Solving: Destination City

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.

Examples

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"
Enter fullscreen mode Exit fullscreen mode

Solution

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:
        all_origins.append(city1)
        all_destinations.append(city2)

    return [d for d in all_destinations if d not in all_origins][0]
Enter fullscreen mode Exit fullscreen mode

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:
        all_origins.add(city1)
        all_destinations.add(city2)

    return (all_destinations - all_origins).pop()
Enter fullscreen mode Exit fullscreen mode

Resources

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay