Minimum Index Sum of Two Lists
Given two arrays of strings representing restaurant preferences for two people, find the common restaurants that appear in both lists and have the smallest index sum. An index sum is the sum of the string's position in list1 plus its position in list2 (0-indexed). If there is a tie for the smallest index sum, return all tied restaurants in any order.
A brute force double loop would compare every pair of entries in O(n * m) time. A hash map approach reduces this to O(n + m): first build a hash map from list1 storing each restaurant's index. Then iterate list2, and for each restaurant that appears in the hash map, compute the index sum. Track the minimum sum seen so far. If a restaurant's sum equals the current minimum, add it to the result. If it's less, start a new result list with just this restaurant.
This is a classic hash map look-up pattern. The map from list1 provides O(1) index lookups, making the overall algorithm linear. It also naturally handles the tie case by collecting restaurants with the same minimum sum.
Edge cases include lists with no common restaurant (return empty array), both lists identical (return all in order of list1 with sum = i + i), and single-element lists that match (return that element).
Example Input & Output
Single common element at sum 0+0=0.
No common restaurants.
Both have sum 1+0=1 and 0+1=1.
Shogun is the only common restaurant at sum 0+3=3.
Shogun sum=0+1=1, KFC sum=3+0=3, Burger King sum=2+2=4.
Algorithm Flow

Solution Approach
Build index map from list1. Iterate list2, check if restaurant is in map, compute sum, track minimum.
Time O(n+m), Space O(n).
Best Answers
import java.util.*;
class Solution {
public String[] solution(String[] list1, String[] list2) {
Map<String,Integer> idx = new HashMap<>();
for (int i = 0; i < list1.length; i++) idx.put(list1[i], i);
int best = Integer.MAX_VALUE;
List<String> res = new ArrayList<>();
for (int j = 0; j < list2.length; j++) {
String w = list2[j];
if (idx.containsKey(w)) {
int sum = idx.get(w) + j;
if (sum < best) { best = sum; res.clear(); res.add(w); }
else if (sum == best) res.add(w);
}
}
return res.toArray(new String[0]);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
