payal-kothari
7/24/2017 - 10:42 PM

From https://leetcode.com/problems/minimum-index-sum-of-two-lists/#/description

public class Solution {
    public String[] findRestaurant(String[] list1, String[] list2) {
        
        Map<String, Integer> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        
        for (int i=0 ; i< list1.length; i++){
            map.put(list1[i], i);
        }
        int min = 2001;
        String[] ans = {" "};
        
        for( int i = 0; i< list2.length; i++){
            if(map.get(list2[i]) != null && i + map.get(list2[i]) <= min) {
                if(i + map.get(list2[i]) < min ){
                    min = i + map.get(list2[i]);
                    list = new ArrayList<>();           // replace the list with new empty list
                }
                list.add(list2[i]);
            } 
        }
        
        return list.toArray(new String[0]);             // convert ArrayList/LinkedList tp String[]
    }
}