Sponsored
Sponsored
The idea is to determine which city does not have any outgoing paths. This can be done by keeping track of all cities that appear as the starting city of a path. The destination city is the one that is not in this set but appears as an ending city in the path list.
Time Complexity: O(n^2) due to linear checks within loops.
Space Complexity: O(n), where n is the number of cities.
1import java.util.HashSet;
2import java.util.List;
3import java.util.Set;
4
5class Solution {
6 public String destCity(List<List<String>> paths) {
7 Set<String> startingCities = new HashSet<>();
8 for (List<String> path : paths) {
9 startingCities.add(path.get(0));
10 }
11 for (List<String> path : paths) {
12 if (!startingCities.contains(path.get(1))) {
13 return path.get(1);
14 }
15 }
16 return "";
17 }
18}
We use a HashSet to store all starting cities, then iterate through the paths to find a city that does not exist in the set as a starting city. This city is the destination city.
This approach involves counting occurrences of each city as an endpoint. The destination city will be the one whose occurrence as a destination is not matched by an occurrence as a start.
Time Complexity: O(n^2), since it includes iterating through paths multiple times.
Space Complexity: O(n) for storing city names.
1using System;
2using System.Collections.Generic;
public class Solution {
public string DestCity(IList<IList<string>> paths) {
Dictionary<string, int> cityCount = new Dictionary<string, int>();
foreach (var path in paths) {
if (!cityCount.ContainsKey(path[0]))
cityCount[path[0]] = 0;
cityCount[path[0]]++;
if (!cityCount.ContainsKey(path[1]))
cityCount[path[1]] = 0;
}
foreach (var path in paths) {
if (cityCount[path[1]] == 0) {
return path[1];
}
}
return "";
}
}
In the C# solution, a dictionary is used to count the number of times a city appears as the starting city. If a city only appears as a destination (count = 0), it is the destination city.