Given two arrays of strings list1 and list2, find the common strings with the least index sum. A common string is a string that appears in both list1 and list2. If it appears at list1[i] and list2[j], its index sum is i + j, and it has the least index sum if no other common string has a smaller one. Return all the common strings with the least index sum, in any order.
Given two arrays of strings list1 and list2, find the common strings with the least index sum. A common string is a string that appears in both list1 and list2. If it appears at list1[i] and list2[j], its index sum is i + j, and it has the least index sum if no other common string has a smaller one. Return all the common strings with the least index sum, 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"]
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, and all the strings of list2 are unique.
There is at least one common string between list1 and list2.
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"list1":["Shogun","Tapioca Express","Burger King","KFC"],"list2":["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]}
Store every list1 string with its position in a hash map (4 entries), so each list2 string can find its partner in O(1).