Skip to content

Commit a9314c1

Browse files
1436 easy java hashset add and contains check
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. Seen this question in a real interview before? 1/5 Yes No Accepted 258.2K Submissions 324.5K Acceptance Rate 79.6% Topics Array Hash Table String
1 parent 8f0ed51 commit a9314c1

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

destination-city.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class Solution {
2+
public String destCity(List<List<String>> paths) {
3+
HashSet<String> set=new HashSet<>();
4+
for(List<String> l:paths)
5+
set.add(l.get(0));
6+
for(List<String> l:paths){
7+
if(!set.contains(l.get(1)))
8+
return l.get(1);
9+
}
10+
return "";
11+
}
12+
}

0 commit comments

Comments
 (0)