Minimum Index Sum of Two Lists (LeetCode 599): Solution and Explanation
Remember where each list1 string sits, then scan list2 and keep every common string whose index sum i + j is the smallest seen.
Intuition
For a common string the cost is its position in list1 plus its position in list2. Comparing every pair would be quadratic, but a hash map from list1 string to index answers "where is it in list1?" instantly.
Walking list2 in order gives j for free. Each hit produces one candidate sum, and the answer is just the running minimum, with ties collected together.
Because j only grows, once j is larger than the best sum found, every later string costs at least j, so the scan can stop early.
Approach: Hash map plus running minimum
- Put every list1 string into a map with its index.
- Set best to infinity and the answer to an empty list.
- For each j in list2, stop if j > best. Skip strings not in the map.
- Compute total = index[s] + j. If total < best, set best = total and reset the answer to [s]. If total == best, append s.
- Return the answer.
Step-by-step example
list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
- Map list1: Shogun 0, Tapioca Express 1, Burger King 2, KFC 3.
- j = 0, 1, 2: Piatti, The Grill at Torrey Pines and Hungry Hunter Steakhouse are not in the map. Skip.
- j = 3: Shogun is at index 0 in list1. Sum 0 + 3 = 3 beats infinity, so best = 3 and the answer is ["Shogun"].
- list2 is finished. The answer is ["Shogun"].
Code: Python, Java, C++
1class Solution:
2 def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
3 index = {s: i for i, s in enumerate(list1)}
4 best = float("inf")
5 result = []
6 for j, s in enumerate(list2):
7 if j > best:
8 break
9 if s not in index:
10 continue
11 total = index[s] + j
12 if total < best:
13 best = total
14 result = [s]
15 elif total == best:
16 result.append(s)
17 return result1class Solution {
2 public String[] findRestaurant(String[] list1, String[] list2) {
3 Map<String, Integer> index = new HashMap<>();
4 for (int i = 0; i < list1.length; i++) index.put(list1[i], i);
5 int best = Integer.MAX_VALUE;
6 List<String> result = new ArrayList<>();
7 for (int j = 0; j < list2.length && j <= best; j++) {
8 Integer i = index.get(list2[j]);
9 if (i == null) continue;
10 int total = i + j;
11 if (total < best) {
12 best = total;
13 result.clear();
14 result.add(list2[j]);
15 } else if (total == best) {
16 result.add(list2[j]);
17 }
18 }
19 return result.toArray(new String[0]);
20 }
21}1class Solution {
2public:
3 vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
4 unordered_map<string, int> index;
5 for (int i = 0; i < (int)list1.size(); i++) index[list1[i]] = i;
6 int best = INT_MAX;
7 vector<string> result;
8 for (int j = 0; j < (int)list2.size() && j <= best; j++) {
9 auto it = index.find(list2[j]);
10 if (it == index.end()) continue;
11 int total = it->second + j;
12 if (total < best) {
13 best = total;
14 result = {list2[j]};
15 } else if (total == best) {
16 result.push_back(list2[j]);
17 }
18 }
19 return result;
20 }
21};Time and space complexity
O(n1 + n2)
Building the map touches list1 once and the scan touches list2 at most once, each step a constant number of hash operations (times the string length, at most 30).
O(n1)
The map holds one entry per list1 string.
Other approaches
Compare every pair (time O(n1 * n2), space O(1))
Two nested loops check list1[i] == list2[j] and track the smallest i + j. Simple, but quadratic.
Scan by sum (time O((n1 + n2)^2), space O(1))
Try sums s = 0, 1, 2, ... and for each check all pairs (i, s - i). The first sum with a match is the answer, but the worst case is still quadratic.
Common mistakes
- Returning only one string when several tie. Every common string with the minimum sum belongs in the answer.
- Forgetting to clear the answer when a strictly smaller sum appears, which leaves stale strings from an older, larger sum.
- Comparing strings case-insensitively. "KFC" and "kfc" are different strings here.
Frequently asked questions
Why is it safe to stop when j > best?
Any string at position j or later has index sum at least j, because its list1 index is at least 0. If j already exceeds the best sum, nothing later can tie or beat it.
Does the order of the returned strings matter?
No. Any order is accepted, so the answer can follow the order in which list2 reveals the ties.
Which list should go into the hash map?
Either works. Putting the shorter list into the map saves memory, but both choices are linear time.