Minimum Index Sum of Two Lists - Problem
Imagine you're a restaurant enthusiast who maintains two favorite restaurant lists, and you want to find the best compromise when dining with a friend! ๐ฝ๏ธ
Given two arrays of strings list1 and list2, find the common restaurants that have the minimum index sum. A common restaurant appears in both lists, and we want to minimize the total "effort" (sum of positions) to find it in both lists.
Goal: Return all common strings where the sum of their indices i + j is minimized across both arrays.
Example: If "Pizza Hut" appears at index 1 in list1 and index 2 in list2, its index sum is 3. We want all restaurants with the smallest possible index sum!
Input & Output
example_1.py โ Basic Case
$
Input:
list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"]
list2 = ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
โบ
Output:
["Shogun"]
๐ก Note:
"Shogun" is the only common restaurant. It appears at index 0 in list1 and index 3 in list2, giving an index sum of 0 + 3 = 3. This is the minimum (and only) sum.
example_2.py โ Multiple Matches
$
Input:
list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"]
list2 = ["KFC", "Shogun", "Burger King"]
โบ
Output:
["Shogun"]
๐ก Note:
Common restaurants: "Shogun" (0+1=1), "Burger King" (2+2=4), "KFC" (3+0=3). "Shogun" has the minimum index sum of 1.
example_3.py โ Tie Case
$
Input:
list1 = ["happy", "sad", "good"]
list2 = ["sad", "happy", "good"]
โบ
Output:
["sad", "happy"]
๐ก Note:
Common restaurants: "happy" (0+1=1), "sad" (1+0=1), "good" (2+2=4). Both "sad" and "happy" have the minimum index sum of 1.
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 strings in list1 are unique
- All strings in list2 are unique
Visualization
Tap to expand
Understanding the Visualization
1
Create Lookup
Build a quick-reference map of your restaurant preferences with their priority rankings
2
Check Friend's List
Go through your friend's list and check if each restaurant is also in your preferences
3
Calculate Compromise
For each mutual restaurant, calculate the 'compromise score' (sum of both rankings)
4
Find Best Options
Collect all restaurants with the lowest compromise score - these are your best dining options!
Key Takeaway
๐ฏ Key Insight: Use a hash table to instantly check if restaurants appear in both lists, then track the minimum index sum to find the best compromise options!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code