Minimum Index Sum of Two Lists

easy hash map string

Problem

Return the common strings between two lists with the smallest index sum (ties allowed).

Inputl1=['S','T','K','H'] l2=['KFC','S','B']
Output['S']
S is at index 0 in l1 and 1 in l2, sum 1.

def find_restaurant(l1, l2):
    idx = {s: i for i, s in enumerate(l1)}
    best, out = 10**9, []
    for j, s in enumerate(l2):
        if s in idx:
            t = idx[s] + j
            if t < best: best, out = t, [s]
            elif t == best: out.append(s)
    return out
function findRestaurant(l1, l2) {
  const idx = new Map(l1.map((s, i) => [s, i]));
  let best = Infinity, out = [];
  l2.forEach((s, j) => {
    if (idx.has(s)) {
      const t = idx.get(s) + j;
      if (t < best) { best = t; out = [s]; }
      else if (t === best) out.push(s);
    }
  });
  return out;
}
String[] findRestaurant(String[] l1, String[] l2) {
    Map idx = new HashMap<>();
    for (int i = 0; i < l1.length; i++) idx.put(l1[i], i);
    int best = Integer.MAX_VALUE; List out = new ArrayList<>();
    for (int j = 0; j < l2.length; j++) if (idx.containsKey(l2[j])) {
        int t = idx.get(l2[j]) + j;
        if (t < best) { best = t; out.clear(); out.add(l2[j]); }
        else if (t == best) out.add(l2[j]);
    }
    return out.toArray(new String[0]);
}
vector findRestaurant(vector& l1, vector& l2) {
    unordered_map idx;
    for (int i = 0; i < (int)l1.size(); i++) idx[l1[i]] = i;
    int best = INT_MAX; vector out;
    for (int j = 0; j < (int)l2.size(); j++) if (idx.count(l2[j])) {
        int t = idx[l2[j]] + j;
        if (t < best) { best = t; out = {l2[j]}; }
        else if (t == best) out.push_back(l2[j]);
    }
    return out;
}
Time: O(n+m) Space: O(n)