Problem Name: 1436. Destination City
Problem Link: https://leetcode.com/problems/destination-city/
Difficulty: Easy
Tag: String | Hash Table
Language: C# | C++
OJ: LeetCode
Algorithm:
1.Initialization:
✅answer is initialized as null. This variable will store the destination city.
✅A Dictionary named map is created to keep track of starting cities. The value associated with each starting city is set to 1.
2.Mark Starting Cities:
✅The first loop iterates through the paths and marks each city at the beginning of a path as a starting city by adding it to the map with a value of 1.
3.Find Destination City:
✅The second loop iterates through the paths again.
✅For each path, it checks if the destination city is not present in the map (not a starting city).
✅If found, it sets the answer to that destination city and breaks out of the loop.
4.Return Result:
✅The method returns the answer, which is the destination city that is not a starting city.
Code(C#)
public class Solution
{
public string DestCity(IList<IList<string>> paths)
{
string answer = null;
var map = new Dictionary<string, int>();
for (int i = 0; i < paths.Count; i++)
map[paths[i][0]] = 1;
for (int i = 0; i < paths.Count; i++)
if (!map.ContainsKey(paths[i][1]))
{
answer = paths[i][1];
break;
}
return answer;
}
}
Code(C++)
Upcoming