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 with the least index sum is a common string such that if it appeared at list1[i] and list2[j] then i + j should be the minimum value among all the other common strings.
Return all thecommon strings with the least index sum. Return the answer in any order.
Input: list1 =["Shogun","Tapioca Express","Burger King","KFC"], list2 =["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]Output: ["Shogun"]Explanation: The only common string is"Shogun".
Input: list1 =["Shogun","Tapioca Express","Burger King","KFC"], list2 =["KFC","Shogun","Burger King"]Output: ["Shogun"]Explanation: The common string with the least index sum is"Shogun"with index sum =(0+1)=1.
Input: list1 =["happy","sad","good"], list2 =["sad","happy","good"]Output: ["sad","happy"]Explanation: There are three common strings:"happy"with index sum =(0+1)=1."sad"with index sum =(1+0)=1."good"with index sum =(2+2)=4.The strings with the least index sum are "sad" and "happy".
To find common strings with the least index sum, we can store the indices of strings from the first list in a hash map, then scan the second list and check for common strings, keeping track of the minimum index sum.
classSolution {
funfindRestaurant(list1: Array<String>, list2: Array<String>): Array<String> {
val idx = list1.withIndex().associate { it.value to it.index }
var mn = Int.MAX_VALUE
val ans = mutableListOf<String>()
for ((j, s) in list2.withIndex()) {
val i = idx[s]
if (i !=null) {
val sum = i + j
if (sum < mn) {
mn = sum
ans.clear()
ans.add(s)
} elseif (sum == mn) {
ans.add(s)
}
}
}
return ans.toTypedArray()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
deffind_restaurant(list1: list[str], list2: list[str]) -> list[str]:
idx = {s: i for i, s in enumerate(list1)}
mn = float('inf')
ans = []
for j, s in enumerate(list2):
if s in idx:
sidx = idx[s] + j
if sidx < mn:
mn = sidx
ans = [s]
elif sidx == mn:
ans.append(s)
return ans