Find the Destination City
💻 coding

Find the Destination City

1 min read 296 words
1 min read
ShareWhatsAppPost on X
  • 1The destination city is defined as the city without any outgoing paths to another city.
  • 2The problem guarantees a linear path structure, ensuring exactly one destination city exists.
  • 3The solution involves using a dictionary to trace paths and identify the final destination.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The destination city is defined as the city without any outgoing paths to another city."

Find the Destination City

You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.

It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.

Example 1:

Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]

Output: "Sao Paulo" 

Explanation: Starting at the "London" city you will reach the "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo".

Example 2:

Input: paths = [["B","C"],["D","B"],["C","A"]]

Output: "A"

Explanation: All possible trips are: 

"D" -> "B" -> "C" -> "A". 

"B" -> "C" -> "A". 

"C" -> "A". 

"A". 

Clearly the destination city is "A".

Example 3:

Input: paths = [["A","Z"]]

Output: "Z"

Constraints:

1 <= paths.length <= 100

paths[i].length == 2

1 <= cityAi.length, cityBi.length <= 10

cityAi != cityBi

All strings consist of lowercase and uppercase English letters and the space character.

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 class DestCitySoln
 {
 public void execute()
 {
 IList<IList<string>> paths = new List<IList<string>>();
 var path = new List<string>();
 path.Add("B");
 path.Add("C");
 paths.Add(path);

 path = new List<string>();
 path.Add("D");
 path.Add("B");
 paths.Add(path);

 path = new List<string>();
 path.Add("C");
 path.Add("A");
 paths.Add(path);

 var res = DestCity(paths);
 }

 public string DestCity(IList<IList<string>> paths)
 {
 var dict = new Dictionary<string, string>();
 for (int i = 0; i < paths.Count; i++)
 {
 dict.Add(paths[i][0], paths[i][1]);
 }

 string finalDest=null;
 string destination = paths[0][1];
 while(destination != null)
 {
 if (dict.ContainsKey(destination))
 {
 destination = dict[destination];
 }
 else
 {
 finalDest = destination;
 destination = null;
 }
 }

 return finalDest;
 }
 }
}

Time Complexity: O(n) - for one iteration.

Space Complexity: O(n) - for storing in hashmap

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 3 May 2020 · 1 min read · 296 words

Part of AskGif Blog · coding

You might also like