## Similar Problems

Similar Problems not available

# Destination City - Leetcode Solution

LeetCode: Destination City Leetcode Solution

Difficulty: Easy

Topics: string hash-table array

The Destination City problem on LeetCode is a straightforward problem that requires identifying the city that cannot be reached by any other city in the given list of city pairs. Here is a detailed solution for the same.

Problem Statement:

You are given a list of city pairs, where each pair represents a direct connection between two cities. Your task is to find the destination city that cannot be reached by any other city.

Solution Approach:

Let's say we have pairs of the form -

[A, B] [C, D] [B, C]

We can represent these pairs as a directed graph, where each node represents a city and each edge represents a direct connection between two cities. In this example, we would have -

A -> B B -> C C -> D

The destination city that cannot be reached by any other city would be the city that has no outgoing edges, as it means that there is no way to reach any other city from that city. Therefore, we can traverse the graph starting from every city and mark the visited cities until we find a city that has no outgoing edges. The last visited city would be the destination city.

Algorithm:

- Initialize a set 'visited' and add all the cities to it.
- Initialize a queue 'queue' with all the source cities (cities that have outgoing edges).
- While the queue is not empty, dequeue a source city and mark it as visited.
- For each destination city connected to the dequeued source city, if it is not visited, enqueue it into the queue.
- The last visited city would be the destination city.

Python Code:

def destCity(paths): # Create a set 'visited' and add all the cities to it visited = set([city for path in paths for city in path])

```
# Get all the source cities (cities that have outgoing edges)
sources = set([path[0] for path in paths])
# Initialize a queue with all the source cities
queue = []
for s in sources:
if s not in visited:
return s
queue.append(s)
# Traverse the graph starting from each source city
while queue:
curr = queue.pop(0)
for path in paths:
if path[0] == curr:
dest = path[1]
if dest not in visited:
visited.add(dest)
queue.append(dest)
# The last visited city would be the destination city
return curr
```

Time Complexity:

The time complexity of this algorithm is O(N^2), where N is the number of city pairs, since we are traversing the graph starting from each source city and checking all the city pairs to find the destination city. However, since N is at most 1000, this algorithm runs in a reasonable time and is sufficient for the given constraints.

## Destination City Solution Code

`1`