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#include <iostream>
2#include <unordered_set>
3#include <vector>
4using namespace std;
5
6string destCity(vector<vector<string>>& paths) {
7 unordered_set<string> starts;
8 for (auto& path : paths) {
9 starts.insert(path[0]);
10 }
11 for (auto& path : paths) {
12 if (starts.find(path[1]) == starts.end()) {
13 return path[1];
14 }
15 }
16 return "";
17}
We use an unordered_set in C++ to efficiently track cities that are starting points. We then simply check each destination to see if it's in the set. The one not found in the set 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;
using 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.