Leetcode 1436: Destination City

grid47
grid47
Exploring patterns and algorithms
Jun 16, 2024 5 min read

You are given an array paths where each element represents a pair of cities [cityAi, cityBi], indicating a direct route from cityAi to cityBi. Your task is to find the destination city, which is the city without any outgoing path to another city.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `paths`, where each element is a pair of strings `[cityAi, cityBi]` representing a direct path from `cityAi` to `cityBi`.
Example: paths = [['Paris', 'Berlin'], ['Berlin', 'Madrid'], ['Madrid', 'Lisbon']]
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.
Output: The output is the name of the destination city, which is the city that does not have any outgoing path.
Example: 'Lisbon'
Constraints:
• The output is a string representing the destination city.
Goal: To find the city that has no outgoing paths by iterating through the `paths` array.
Steps:
• Step 1: Create a set to store cities with outgoing paths.
• Step 2: For each pair in the `paths` array, mark `cityAi` as having an outgoing path.
• Step 3: The city that is not in the set of cities with outgoing paths is the destination city.
Goal: Ensure that the solution efficiently handles paths with up to 100 pairs.
Steps:
• The solution should handle up to 100 paths.
• Strings have a length of up to 10 characters.
Assumptions:
• The input paths array contains valid pairs of strings.
• The graph of cities forms a line with no loops.
Input: paths = [['Paris', 'Berlin'], ['Berlin', 'Madrid'], ['Madrid', 'Lisbon']]
Explanation: Starting from 'Paris', we reach 'Lisbon' by traveling through 'Berlin' and 'Madrid'. 'Lisbon' is the destination city as it has no outgoing path.

Input: paths = [['A', 'B'], ['B', 'C'], ['C', 'D']]
Explanation: Following the path 'A' -> 'B' -> 'C' -> 'D', we find that 'D' is the destination city as there is no path from it to another city.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus