1436. Destination City
You are given the arraypaths
, wherepaths[i] = [cityAi, cityBi]
means there exists a direct path going fromcityAi
tocityBi
. Return 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.
Example 1:
- 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".
solv
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
source_cities = set(cityA for cityA, cityB in paths)
# Iterate over the paths and find the destination city
for cityA, cityB in paths:
if cityB not in source_cities:
return cityB
The code for this problem looks soo easy. The destination shouldn't be appeared in cityA. So the source cities which contain cityAs in all the paths, don't have the answer destination we want. There is no need to search the paths to the destination, but all we need to do is setting the cityAs and find which city didn't appeared in cityB.
So easy.. think easy and make the code easier.