You have two lists, list1
and list2
, both of which contain strings representing restaurant names. Your task is to find the common interest with the least index sum. A common interest in these two lists means that both lists contain the same restaurant. The index sum of a common interest is the sum of the indices of the common interest in list1
and list2
. If there is a tie, return all restaurants with the lowest index sum in a list. If there are no common interests, return an empty list.
list1
and list2
?list1
.list2
and for each restaurant, calculate the sum of indices if it is found in list1
.list1
: O(n)list2
and checking against the dictionary: O(m)def findRestaurant(list1, list2):
index_map_list1 = {restaurant: index for index, restaurant in enumerate(list1)}
min_sum = float('inf')
result = []
for index2, restaurant in enumerate(list2):
if restaurant in index_map_list1:
index1 = index_map_list1[restaurant]
current_sum = index1 + index2
if current_sum < min_sum:
min_sum = current_sum
result = [restaurant]
elif current_sum == min_sum:
result.append(restaurant)
return result
# Example Usage
list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"]
list2 = ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
print(findRestaurant(list1, list2)) # Output: ["Shogun"]
list1
to its index.list2
, we check if it exists in list1
using the dictionary.This solution efficiently finds the common interests in the two lists and solves the problem within the expected time complexity limits.
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?