Sunday, March 7, 2021

Leetcode Everyday: 1436. Destination City. Easy

public class Solution {
    public string DestCity(IList<IList<string>> paths) {
        var pathLookup = new Dictionary<string, string>();
        
        foreach (var path in paths) {
            pathLookup[path.First()] = path.Last();
        }
        
        var source = pathLookup.FirstOrDefault().Key;
        while (pathLookup.TryGetValue(source, out string destination)) {
            source = destination;
        }   
        
        return source;
    }
}
Functional programming:
public class Solution {
    public string DestCity(IList<IList<string>> paths) =>        
        paths.Single(dest => !paths.Any(source => dest.Last() == source.First())).Last();
}
Optimized:
public class Solution {
    public string DestCity(IList<IList<string>> paths) {
        var outgoing = new HashSet<string>();        
        outgoing.UnionWith(paths.Select(path => path.First()));
        
        foreach (var path in paths) {
            if (!outgoing.Contains(path.Last())) {
                return path.Last();
            }
        }
        
        return null;
    }
}
Source: https://leetcode.com/problems/destination-city/submissions/

No comments:

Post a Comment