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
Finding the Destination CityFollow the chain of cities to find where the journey endsSTARTLondonSource onlyMIDDLENew YorkSource & DestMIDDLELimaSource & DestENDSao PauloDestination only๐ŸŽฏ Key InsightThe destination city appears in paths as a targetbut never appears as a source city.Use a hash set to track sources, then find the missing destination!Time Complexity: O(n) | Space Complexity: O(n)
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.
Asked in
Amazon 15 Google 8 Microsoft 5 Apple 3
98.0K Views
Medium Frequency
~12 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen