package leetcode;

/**
 * https://leetcode.com/problems/minimum-index-sum-of-two-lists/#/description
 */
public class Problem577 {
    public String[] findRestaurant(String[] list1, String[] list2) {
        // TODO
        return null;
    }

    public static void main(String[] args) {
        Problem577 prob = new Problem577();
        System.out.println(prob.findRestaurant(
            new String[]{"Shogun", "Tapioca Express", "Burger King", "KFC"},
            new String[]{"Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"})); // Shogun
        System.out.println(prob.findRestaurant(
            new String[]{"Shogun", "Tapioca Express", "Burger King", "KFC"},
            new String[]{"KFC", "Shogun", "Burger King"})); // Shogun
    }
}

package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * https://leetcode.com/problems/minimum-index-sum-of-two-lists/#/description
 */
public class Problem577 {
    public String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < list1.length; i++) {
            map.put(list1[i], i);
        }
        int min = 0;
        boolean init = true;
        List<String> result = new ArrayList<>();
        for (int i = 0; i < list2.length; i++) {
            if (map.containsKey(list2[i])) {
                int sum = map.get(list2[i]) + i;
                if ((min == 0 && init) || min > sum) {
                    min = sum;
                    result = new ArrayList<>();
                    result.add(list2[i]);
                    init = false;
                } else if (sum == min) {
                    result.add(list2[i]);
                }
            }
        }
        return result.toArray(new String[0]);
    }
}

Solve problem 577