[LeetCode]#1436. Destination City

Fatboy Slim
1 min readMay 6, 2020

--

Environment: Python 3.7

Key technique: collections.defaultdict, Hash Table

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 2:

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

Analysis:

  1. Create Hash Table for path
  2. Search all string list in Hash Table
  3. If string doesn’t have pair, return it.

Solution:

import collections
class Solution:
def destCity(self, paths):
hashtable = collections.defaultdict(str)

ls = []

for a,b in paths:
hashtable[a] = b
ls += a,
ls += b,

for ans in ls:
if hashtable[ans] == "":
return ans

Submissions:

Reference:

https://leetcode.com/problems/destination-city/discuss/615132/Python-Easy-to-Understand-solution-(-Using-hashmap-)

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet