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.
1
This Python solution uses a set to track each of the starting cities. For each path, it checks if the destination is not in the set of starting cities. The first such city found 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.
1#include <string>
2#include <vector>
3#include <unordered_map>
4using namespace std;
5
6string destCity(vector<vector<string>>& paths) {
7 unordered_map<string, int> cityCount;
8 for (auto& path : paths) {
9 cityCount[path[0]]++;
10 if (cityCount.find(path[1]) == cityCount.end()) {
11 cityCount[path[1]] = 0;
12 }
13 }
14 for (auto& path : paths) {
15 if (cityCount[path[1]] == 0) {
16 return path[1];
17 }
18 }
19 return "";
20}
In this C++ solution, we maintain a hashmap to count how many times a city appears as a start and ensure every destination is initialized in the map. The destination city will have a count of 0, indicating it never appears as a start.