LeetCode 1436: Destination City Solution

Master LeetCode problem 1436 (Destination City), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1436. Destination City

Problem Explanation

Explanation

To find the destination city, we can create a set of all cities that are the starting point of a path. Then we iterate through all the cities in the paths array and check if they are not in the set of starting cities. The city that is not a starting city is the destination city.

Algorithm:

  1. Create a set to store starting cities.
  2. Iterate through the paths array and add the first city of each path to the set.
  3. Iterate through the paths array again and check if the second city of each path is not in the set of starting cities. This city is the destination city.

Time Complexity: O(n), where n is the number of paths.

Space Complexity: O(n), to store the set of starting cities.

Solution Code

class Solution {
    public String destCity(List<List<String>> paths) {
        Set<String> startingCities = new HashSet<>();
        
        for (List<String> path : paths) {
            startingCities.add(path.get(0));
        }
        
        for (List<String> path : paths) {
            if (!startingCities.contains(path.get(1))) {
                return path.get(1);
            }
        }
        
        return "";
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1436 (Destination City)?

This page provides optimized solutions for LeetCode problem 1436 (Destination City) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1436 (Destination City)?

The time complexity for LeetCode 1436 (Destination City) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1436 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1436 in Java, C++, or Python.

Back to LeetCode Solutions