algoadvance

Problem Clarification:

The problem normally described as “1436. Destination City” can be summarized as follows:

Key Constraints:

  1. The given paths will form a single valid itinerary without cycles.
  2. There will be exactly one destination city.

Clarifying Questions:

  1. Can each city appear in both paths as a destination and a start other than the final destination city?
  2. Are there any constraints on the number of paths, or specific edge cases, like very large input sizes that I need to handle?

Strategy:

  1. Extract all the cities that have outgoing paths (start_cities).
  2. Simultaneously, collect cities that have incoming paths (end_cities).
  3. The destination city is the one which appears in the end_cities set but not in the start_cities set.

Approach:

Time Complexity:

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:

  1. start_cities keeps track of all cities from which a path starts.
  2. end_cities keeps track of all cities where a path ends.
  3. 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.

Try our interview co-pilot at AlgoAdvance.com