Destination City - Problem
Imagine you're planning a one-way road trip where each city connects to exactly one other city, forming a single chain of destinations. You're given an array of travel paths where each path paths[i] = [cityAi, cityBi] represents a direct route from cityAi to cityBi.
Your task is to find the destination city - the final stop where your journey ends. This is the city that has no outgoing paths to any other city.
Key Points:
- The paths form a linear chain without any loops
- There's exactly one starting city (no incoming paths) and one destination city (no outgoing paths)
- Every other city has exactly one incoming and one outgoing path
Goal: Return the name of the destination city as a string.
Input & Output
example_1.py โ Basic Linear Chain
$
Input:
[["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
โบ
Output:
"Sao Paulo"
๐ก Note:
Starting from London, we can travel to New York, then to Lima, and finally to Sao Paulo. Since there's no path leaving Sao Paulo, it's the destination city.
example_2.py โ Simple Two-City Chain
$
Input:
[["B","C"],["D","B"],["C","A"]]
โบ
Output:
"A"
๐ก Note:
The path is D โ B โ C โ A. City A has no outgoing paths, making it the final destination.
example_3.py โ Single Path Edge Case
$
Input:
[["A","Z"]]
โบ
Output:
"Z"
๐ก Note:
With only one path from A to Z, Z is clearly the destination since it has no outgoing connections.
Constraints
- 1 โค paths.length โค 100
- paths[i].length == 2
- 1 โค cityAi, cityBi โค 10
- cityAi != cityBi
- All city names consist of lowercase and uppercase English letters and the space character
- The graph of paths forms a line without any loops
Visualization
Tap to expand
Understanding the Visualization
1
Map the Routes
Each path shows a one-way connection between cities
2
Find the Pattern
Most cities appear both as sources and destinations
3
Identify the End
The destination city only appears as a target, never as a source
Key Takeaway
๐ฏ Key Insight: The destination city is the only city that appears as a path target but never as a path source. Using a hash set to track sources allows us to find this city efficiently in O(n) time.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code