Index the first list in a map, scan the second list, and keep only matches tied for the smallest combined index.
Complexity
O(n + m) time and O(n) space for list lengths n and m.
Return common restaurants whose index sum across two preference lists is minimal.
Index the first list in a map, scan the second list, and keep only matches tied for the smallest combined index.
O(n + m) time and O(n) space for list lengths n and m.
package main
func findRestaurant(list1 []string, list2 []string) []string {
firstIndex := make(map[string]int, len(list1))
for index, name := range list1 {
firstIndex[name] = index
}
result := []string{}
best := int(^uint(0) >> 1)
for index, name := range list2 {
other, ok := firstIndex[name]
if !ok {
continue
}
sum := index + other
if sum < best {
best, result = sum, []string{name}
} else if sum == best {
result = append(result, name)
}
}
return result
}
class Solution:
def findRestaurant(self, list1: list[str], list2: list[str]) -> list[str]:
first_index = {name: index for index, name in enumerate(list1)}
result: list[str] = []
best = float("inf")
for index, name in enumerate(list2):
if name not in first_index:
continue
index_sum = index + first_index[name]
if index_sum < best:
best, result = index_sum, [name]
elif index_sum == best:
result.append(name)
return result
function findRestaurant(list1: string[], list2: string[]): string[] {
const firstIndex = new Map(list1.map((name, index) => [name, index]));
const result: string[] = [];
let best = Number.POSITIVE_INFINITY;
for (let index = 0; index < list2.length; index += 1) {
const other = firstIndex.get(list2[index]);
if (other === undefined) continue;
const sum = index + other;
if (sum < best) { best = sum; result.length = 0; result.push(list2[index]); }
else if (sum === best) result.push(list2[index]);
}
return result;
}