1436. Destination City
Description
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.
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 <= 100
paths[i].length == 2
1 <= cityAi.length, cityBi.length <= 10
cityAi != cityBi
- All strings consist of lowercase and uppercase English letters and the space character.
Solutions
Solution 1: Hash Table
According to the problem description, the destination city will not appear in any of the $\textit{cityA}$. Therefore, we can first traverse the $\textit{paths}$ and put all $\textit{cityA}$ into a set $\textit{s}$. Then, we traverse the $\textit{paths}$ again to find the $\textit{cityB}$ that is not in $\textit{s}$.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the length of $\textit{paths}$.
Python3
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)
Java
class Solution {
public String destCity(List<List<String>> paths) {
Set<String> s = new HashSet<>();
for (var p : paths) {
s.add(p.get(0));
}
for (int i = 0;; ++i) {
var b = paths.get(i).get(1);
if (!s.contains(b)) {
return b;
}
}
}
}
C++
class Solution {
public:
string destCity(vector<vector<string>>& paths) {
unordered_set<string> s;
for (auto& p : paths) {
s.insert(p[0]);
}
for (int i = 0;; ++i) {
auto b = paths[i][1];
if (!s.contains(b)) {
return b;
}
}
}
};
Go
func destCity(paths [][]string) string {
s := map[string]bool{}
for _, p := range paths {
s[p[0]] = true
}
for _, p := range paths {
if !s[p[1]] {
return p[1]
}
}
return ""
}
TypeScript
function destCity(paths: string[][]): string {
const s = new Set<string>(paths.map(([a, _]) => a));
return paths.find(([_, b]) => !s.has(b))![1];
}
Rust
use std::collections::HashSet;
impl Solution {
pub fn dest_city(paths: Vec<Vec<String>>) -> String {
let s = paths
.iter()
.map(|p| p[0].clone())
.collect::<HashSet<String>>();
paths.into_iter().find(|p| !s.contains(&p[1])).unwrap()[1].clone()
}
}
JavaScript
/**
* @param {string[][]} paths
* @return {string}
*/
var destCity = function (paths) {
const s = new Set(paths.map(([a, _]) => a));
return paths.find(([_, b]) => !s.has(b))[1];
};