#1436

Destination City

Easy
ArrayHash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a set to track outgoing paths and directly identifies the destination city in a single pass. This is efficient and avoids redundant checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a set to store all cities with outgoing paths.
  2. 2Step 2: Populate the set with all starting cities from the paths.
  3. 3Step 3: Iterate through the paths again and check which city is not in the set. That city is the destination.
solution.py3 lines
1def destCity(paths):
2    outgoing = set(cityA for cityA, cityB in paths)
3    return next(cityB for cityA, cityB in paths if cityB not in outgoing)

Complexity note: The time complexity is O(n) because we iterate through the paths twice, while the space complexity is O(n) due to the storage of outgoing paths.

  • 1The destination city is the only city that does not appear as a starting point in any path.
  • 2Using a set for efficient lookups allows us to reduce the time complexity significantly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.