Problem Description
Given an array paths where each element is a pair of cities [cityA, cityB] representing a one-way direct path from cityA to cityB, return the destination city. The destination city is defined as the city that does not have any outgoing paths.
Key Insights
- The problem guarantees that the paths form a simple line without loops.
- The destination city will never appear as a source city (i.e., the first element of any pair).
- By gathering all source cities in a set, one can iterate through the destinations to find the one that is not in the source set.
- The problem can be solved in O(n) time using a single pass over the list.
Space and Time Complexity
Time Complexity: O(n), where n is the number of paths. Space Complexity: O(n), for storing the set of source cities.
Solution
The approach is to first create a set of all cities that appear as a source (the first element in each pair). Then, iterate through each pair and check if the destination city (the second element) is not in the set of source cities. Since the list of paths forms a simple linear graph without loops, exactly one city will satisfy this condition, and that is the destination city.