Destination City - Problem

You are given an array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi.

Return the destination city, that is, the city without any path outgoing to another city.

It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.

Input & Output

Example 1 — Basic Chain
$ Input: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]
Output: "Sao Paulo"
💡 Note: Following the path: London → New York → Lima → Sao Paulo. Sao Paulo has no outgoing path, so it's the destination.
Example 2 — Simple Path
$ Input: paths = [["B","C"],["D","B"],["C","A"]]
Output: "A"
💡 Note: The path is D → B → C → A. City A appears as a destination but never as a source.
Example 3 — Single Path
$ Input: paths = [["A","Z"]]
Output: "Z"
💡 Note: Only one path A → Z, so Z is the destination city with no outgoing paths.

Constraints

  • 1 ≤ paths.length ≤ 100
  • paths[i].length == 2
  • 1 ≤ cityAi.length, cityBi.length ≤ 10
  • cityAi ≠ cityBi
  • All strings consist of lowercase and uppercase English letters and the space character.

Visualization

Tap to expand
Destination City - Hash Set Optimization INPUT paths = [...] ["London", "New York"] London --> New York ["New York", "Lima"] New York --> Lima ["Lima", "Sao Paulo"] Lima --> Sao Paulo Path Graph: London New York Lima Sao Paulo ALGORITHM STEPS 1 Create Source Set Store all source cities sources = {London, New York, Lima} 2 Collect Destinations Get all destination cities dests = {New York, Lima, Sao Paulo} 3 Find Difference dest NOT in sources = answer New York in sources? YES Lima in sources? YES Sao Paulo in sources? NO 4 Return Result City with no outgoing path return "Sao Paulo" FINAL RESULT The destination city is: "Sao Paulo" Why Sao Paulo? - London has outgoing path - New York has outgoing path - Lima has outgoing path - Sao Paulo has NO outgoing Output Verification: OK - Correct! Time: O(n) | Space: O(n) Key Insight: The destination city appears ONLY as a destination, never as a source. By storing all source cities in a HashSet, we can quickly check each destination - the one NOT in the source set is our answer. HashSet provides O(1) lookup, making the overall solution O(n) time complexity. TutorialsPoint - Destination City | Hash Set Optimization Approach
Asked in
Google 15 Amazon 12 Apple 8 Facebook 6
31.5K Views
Medium Frequency
~10 min Avg. Time
892 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