Minimum Index Sum of Two Lists
Solution to Isomorphic Strings problem.
class Solution {
public String[] findRestaurant(String[] list1, String[] list2) {
Map<String, Integer> list2Map = listToMap(list2);
List<String> result = new ArrayList<>();
int previousMatchScore = Integer.MAX_VALUE;
for(int i=0;i<list1.length;i++) {
if (list2Map.get(list1[i]) != null) {
int score = i + list2Map.get(list1[i]);
if (score <= previousMatchScore) {
previousMatchScore = score;
result.add(list1[i]);
}
}
}
return result.toArray(new String[result.size()]);
}
private Map<String, Integer> listToMap(String[] list) {
Map<String, Integer> listMap = new LinkedHashMap<>();
for(int i=0;i<list.length;i++) {
listMap.put(list[i], i);
}
return listMap;
}
}