Destination City Problem
Description
LeetCode Problem 1436.
You are given the array paths, where paths[i] = [cityA_i, cityB_i] means there exists a direct path going from cityA_i to cityB_i. 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".
Example 2:
Input: paths = [["B","C"],["D","B"],["C","A"]]
Output: "A"
Explanation: All possible trips are:
"D" -> "B" -> "C" -> "A".
"B" -> "C" -> "A".
"C" -> "A".
"A".
Clearly the destination city is "A".
Example 3:
Input: paths = [["A","Z"]]
Output: "Z"
Constraints:
1 <= paths.length <= 100paths[i].length == 21 <= cityA_i.length, cityB_i.length <= 10cityA_i != cityB_i- All strings consist of lowercase and uppercase English letters and the space character.
Solution
Approach: Hash Set of Start Cities
The destination is the only city with no outgoing path, so it never appears as cityA. Put every cityA in a hash set, then return the cityB that is not in the set.
The problem guarantees the paths form one line, so exactly one such cityB exists. City names can contain spaces ("New York"), which is fine since we compare whole strings.
Complexity: O(n) time and O(n) extra space, counting each name comparison as O(1) (names have at most 10 characters).
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
starts = {a for a, _ in paths} # every city with an outgoing path
for _, b in paths:
if b not in starts:
return b
return "" # the problem guarantees a destination, so this is never reached