Problem Clarification:
The problem normally described as “1436. Destination City” can be summarized as follows:
- We are given a list of directed paths between cities.
- Each path is represented as a list of two cities [A, B], meaning there’s a direct route from city A to city B.
- The objective is to determine the destination city, which is the city that does not have any outgoing paths but can have incoming paths.
Key Constraints:
- The given paths will form a single valid itinerary without cycles.
- There will be exactly one destination city.
Clarifying Questions:
- Can each city appear in both paths as a destination and a start other than the final destination city?
- Are there any constraints on the number of paths, or specific edge cases, like very large input sizes that I need to handle?
Strategy:
- Extract all the cities that have outgoing paths (
start_cities
).
- Simultaneously, collect cities that have incoming paths (
end_cities
).
- The destination city is the one which appears in the
end_cities
set but not in the start_cities
set.
Approach:
- Use two sets: one for start cities and one for end cities.
- Iterate through the list of paths to populate these sets.
- The city present in the
end_cities
set but not in the start_cities
set is the destination city.
Time Complexity:
- Constructing the sets involves iterating through the list once, resulting in O(n) time complexity, where n is the number of paths.
- Space complexity is O(n) due to storage of cities in sets, assuming unique cities grow linearly with the number of paths.
Code:
def destCity(paths):
start_cities = set()
end_cities = set()
# Populate the sets
for start, end in paths:
start_cities.add(start)
end_cities.add(end)
# Find the city in end_cities that is not in start_cities
for city in end_cities:
if city not in start_cities:
return city
# Example usage
paths = [["London", "New York"], ["New York", "Lima"], ["Lima", "Sao Paulo"]]
print(destCity(paths)) # Output: "Sao Paulo"
Explanation:
start_cities
keeps track of all cities from which a path starts.
end_cities
keeps track of all cities where a path ends.
- The destination city is the one that exists in
end_cities
but not in start_cities
.
This method efficiently determines the destination city in a single pass through the paths list, making it optimal for large datasets as well.
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?