본문 바로가기
Problem Solving/LeetCode

[LeetCode] 599. Minimum Index Sum of Two Lists - Java

by graycode 2026. 9. 10.

• 문제 링크

 

Minimum Index Sum of Two Lists - LeetCode

Can you solve this real interview question? Minimum Index Sum of Two Lists - Given two arrays of strings list1 and list2, find the common strings with the least index sum. A common string is a string that appeared in both list1 and list2. A common string w

leetcode.com

 

• 풀이 코드

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

public class Solution {

    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);

        List<String> list = new ArrayList<>();
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < list2.length; i++) {
            if (!map.containsKey(list2[i])) continue;

            int sum = map.get(list2[i]) + i;
            if (sum < min) {
                list.clear();
                list.add(list2[i]);
                min = sum;
            } else if (sum == min) list.add(list2[i]);
        }

        return list.toArray(new String[0]);
    }

}

댓글