Minimum Index Sum of Two Lists - Problem
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.
Input & Output
Example 1 — 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" appears at index 0 in list1 and index 3 in list2, giving sum 0+3=3. This is the only common string with the minimum index sum.
Example 2 — Multiple Results
$
Input:
list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"]
›
Output:
["Shogun","KFC"]
💡 Note:
"Shogun" has sum 0+1=1, "KFC" has sum 3+0=3, "Burger King" has sum 2+2=4. "Shogun" has minimum sum, but wait - "KFC" has sum 3, not 1. Actually "Shogun" sum is 0+1=1, "KFC" sum is 3+0=3, "Burger King" sum is 2+2=4. Only "Shogun" has minimum sum 1.
Example 3 — Single Match
$
Input:
list1 = ["happy","sad","good"], list2 = ["sad","happy","good"]
›
Output:
["sad","happy","good"]
💡 Note:
"happy": 0+1=1, "sad": 1+0=1, "good": 2+2=4. Both "sad" and "happy" have minimum sum 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 the strings of list1 are unique.
- All the strings of list2 are unique.
Visualization
Tap to expand
Understanding the Visualization
1
Input Lists
Two arrays of restaurant preferences in order
2
Find Common
Identify strings that appear in both lists
3
Calculate Sums
Add position indices for each common string
4
Minimum Sum
Return all strings with the smallest index sum
Key Takeaway
🎯 Key Insight: Use hash map to efficiently find common strings and track minimum index sum in one pass
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code