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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public string DestCity(IList<IList<string>> paths) {
6 HashSet<string> startingCities = new HashSet<string>();
7 foreach (var path in paths) {
8 startingCities.Add(path[0]);
9 }
10 foreach (var path in paths) {
11 if (!startingCities.Contains(path[1])) {
12 return path[1];
13 }
14 }
15 return "";
16 }
17}
In C#, we use a HashSet to track cities that are starting points. The approach follows similar logic to C++, adding and checking elements in the set appropriately to find 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.
1import
In this Java approach, a hashmap maintains the count of outgoing paths from each city. Initially, cities as destinations are set to 0. We then determine which city is never a start city.