Destination City — LeetCode 1436 Python Solution

EasyArrayHash TableString
Problem
#1436
Pattern
Hash Map
Reading time
2 min

The problem

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

Example

Input
paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
Output
"Sao Paulo"
Explanation
Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo".

Python solution

Python
class Solution:
    def destCity(self, paths: List[List[str]]) -> str:
        s = {a for a, _ in paths}
        return next(b for _, b in paths if b not in s)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1436. Destination City is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1436. Destination City?
LeetCode 1436. Destination City is rated Easy on LeetCode.
What is the time complexity of LeetCode 1436. Destination City?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1436. Destination City?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1436. Destination City cover?
LeetCode 1436. Destination City is tagged Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview