Destination City — LeetCode 1436 Python Solution
- Problem
- #1436
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.