Destination City
Destination City – A Simple Graph Traversal Insight
Problem Statement
You are given a list of paths
, where each paths[i] = [cityAi, cityBi]
represents a direct path from city Ai
to city Bi
. The cities form a straight-line route with no cycles or branches.
Your task is to find the destination city—the one with no outgoing path.
It is guaranteed that the graph forms a valid line and has exactly one such city.
Examples
Input:
[["London", "New York"], ["New York", "Lima"], ["Lima", "Sao Paulo"]]
Output:
"Sao Paulo"
Best Data Structure for the Job
A HashSet is ideal for efficiently storing all source cities.
Any city that appears only as a destination and never as a source is the final destination.
Different Approaches
Approach 1: Brute Force
This method checks for each destination city if it never appears as a source. It does this using nested loops.
Approach 2: Map-Based Traversal
We treat the path as a mapping from one city to the next. Start from any city with an outgoing path and keep following the chain until there’s no next city.
Approach 3: HashSet Filtering
This is the most optimized solution. You only care about which cities are sources (i.e., have outgoing paths). The destination city is the only one that is never a source.
⚠️Common Mistakes and Pitfalls
-
Forgetting that the destination city is one that never appears as a source.
-
Overcomplicating the problem with graph traversal techniques like DFS or BFS.
-
Mishandling input when there's only one path (e.g.,
[["A", "Z"]]
), though the problem guarantees a valid input
📊 Time and Space Complexity Comparison
Approach | Time Complexity | Space Complexity |
---|---|---|
Brute Force | O(n²) | O(1) |
Map-Based Traversal | O(n) | O(n) |
HashSet Filtering | O(n) | O(n) |
🌍Real-world Applications
-
Travel planning systems identifying final destinations
-
Supply chain and logistics tracking endpoints
-
Workflow automation where the terminal step needs to be identified
-
Analyzing route data in transportation networks
I hope you found this article insightful! Keep exploring, keep learning, and don’t forget to check back daily for more exciting problem breakdowns. If you know someone who would benefit from this, share it with them and help them grow too! That’s it for today—see you in the next post!
Signing off!!
Master DSA One Problem at a Time :)
Comments
Post a Comment