Destination City

easy hash map hash set

Problem

You're given an array paths of [from, to] city pairs that describe a route. Exactly one city is never the start of any path — that's the final destination. Return it.

Inputpaths = [["London","NY"],["NY","LA"],["LA","SF"]]
Output"SF"
SF appears as destination but never as a source.

def dest_city(paths):
    sources = {a for a, _ in paths}
    for _, b in paths:
        if b not in sources:
            return b
    return ""
function destCity(paths) {
  const sources = new Set();
  for (const [a, _] of paths) sources.add(a);
  for (const [_, b] of paths) {
    if (!sources.has(b)) return b;
  }
  return "";
}
class Solution {
    public String destCity(List<List<String>> paths) {
        Set<String> sources = new HashSet<>();
        for (var p : paths) sources.add(p.get(0));
        for (var p : paths) {
            if (!sources.contains(p.get(1))) return p.get(1);
        }
        return "";
    }
}
string destCity(vector<vector<string>>& paths) {
    unordered_set<string> sources;
    for (auto& p : paths) sources.insert(p[0]);
    for (auto& p : paths) {
        if (!sources.count(p[1])) return p[1];
    }
    return "";
}
Time: O(n) Space: O(n)