Leetcode 599. Minimum Index Sum of Two Lists
The problem is as follows:
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.
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 restaurant is "Shogun" with index sum 0 (3 + 0).
Example 2:
Input: list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"], list2 = ["KFC", "Shogun", "Burger King"] Output: ["Shogun"] Explanation: The restaurant that has the least index sum is "Shogun" with index sum 1 (0 + 1).
Constraints:
1 <= list1.length, list2.length <= 1000
1 <= list1[i].length, list2[i].length <= 30
list1[i]
andlist2[i]
consist of spaces' '
and English letters.- All the strings in
list1
are unique.- All the strings in
list2
are unique.
list1
: Create a map where the key is the restaurant name and the value is its index in list1
.list2
: For each restaurant in list2
, check if it is present in the map created from list1
.list2
, return the resultant list of restaurants with the minimum index sum.Here’s the implementation in C++:
#include <vector>
#include <string>
#include <unordered_map>
#include <climits>
class Solution {
public:
std::vector<std::string> findRestaurant(std::vector<std::string>& list1, std::vector<std::string>& list2) {
std::unordered_map<std::string, int> indexMap;
for (int i = 0; i < list1.size(); ++i) {
indexMap[list1[i]] = i;
}
std::vector<std::string> result;
int minSum = INT_MAX;
for (int j = 0; j < list2.size(); ++j) {
if (indexMap.find(list2[j]) != indexMap.end()) {
int sum = j + indexMap[list2[j]];
if (sum < minSum) {
result.clear();
result.push_back(list2[j]);
minSum = sum;
} else if (sum == minSum) {
result.push_back(list2[j]);
}
}
}
return result;
}
};
O(n)
where n
is the length of list1
.list2
: O(m)
where m
is the length of list2
.list2
are two separate linear passes, the total time complexity is O(n + m)
.This should offer efficient performance for the problem constraints provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?