599. Minimum Index Sum of Two Lists
DifficultyEasy
Description
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.
Example 3:
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".
Constraints:
1 <= list1.length, list2.length <= 10001 <= list1[i].length, list2[i].length <= 30list1[i]andlist2[i]consist of spaces' 'and English letters.- All the strings of
list1are unique. - All the strings of
list2are unique. - There is at least a common string between
list1andlist2.
Solutions
Solution 1: Hash Table
Thinking
Among common strings, keep those with the smallest index sum. Scanning the other list for every common string is \(O(nm)\).
Map \(\textit{list2}\) from string to index, then scan \(\textit{list1}\) for sums. Keep the current minimum: append on a tie, reset on a smaller sum. One hash build and one linear scan.
We use a hash table \(d\) to record the strings in \(\textit{list2}\) and their indices, and a variable \(mi\) to record the minimum index sum.
Then, we traverse \(\textit{list1}\). For each string \(s\), if \(s\) appears in \(\textit{list2}\), we calculate the index \(i\) of \(s\) in \(\textit{list1}\) and the index \(j\) in \(\textit{list2}\). If \(i + j < mi\), we update the answer array \(\textit{ans}\) to \(s\) and update \(mi\) to \(i + j\). If \(i + j = mi\), we add \(s\) to the answer array \(\textit{ans}\).
After traversing, return the answer array \(\textit{ans}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |