Leetcode 1436. Destination City
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
. Where cityA_i
is the starting point and cityB_i
is the destination.
Return the destination city, that is, the city without any path outgoing from it.
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.
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 has no outgoing path.
paths
?
paths
can typically be assumed to be 100.import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Solution {
public String destCity(List<List<String>> paths) {
Set<String> startingCities = new HashSet<>();
// Add all starting cities to the set
for (List<String> path : paths) {
startingCities.add(path.get(0));
}
// Check each ending city to see if it's not in the set of starting cities
for (List<String> path : paths) {
String endCity = path.get(1);
if (!startingCities.contains(endCity)) {
return endCity;
}
}
// The problem guarantees there will always be a destination city,
// so it's safe to return null or a default value here.
return null;
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?