Minimum Index Sum of Two Lists
# 599. 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 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 the common strings with the least index sum. Return the answer in any order.
### Example 1: ``` 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". ``` ### Example 2: ``` 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. ``` Constraints: ``` 1 <= list1.length, list2.length <= 1000 1 <= list1[i].length, list2[i].length <= 30 list1[i] and list2[i] consist of spaces ' ' and English letters. All the strings of list1 are unique. All the strings of list2 are unique. ```
/** * @param {string[]} list1 * @param {string[]} list2 * @return {string[]} */ var findRestaurant = function(list1, list2) { const map = new Map(); const getFreqMap = (arr) => { for(let i = 0; i < arr.length; i++) { if (map.has(arr[i])) { const val = map.get(arr[i]).split(':'); map.set(arr[i], `${+val[0] + 1}:${+val[1] + i}`); } else { map.set(arr[i], `1:${i}`); } } } getFreqMap(list1); getFreqMap(list2); const freq = 2; let min = Infinity, out = []; for(const [key, value] of map.entries()) { const valParts = value.split(':'); if (+valParts[0] === freq) { if (+valParts[1] < min) { out = [key]; min = +valParts[1]; } else if (+valParts[1] === min) { out.push(key); } } } return out; };