Leetcode 599. Minimum Index Sum of Two Lists Sure! Let’s break down the problem-solving process for LeetCode problem 599, “Minimum Index Sum of Two Lists.”
Given two lists list1
and list2
of strings, find the common strings with the least index sum. If there is a tie, output all the strings with the minimum index sum.
Presuming the following:
list1
.list2
and for each string, check if it exists in list1
.import java.util.*;
public class Solution {
public String[] findRestaurant(String[] list1, String[] list2) {
// Step 1: Create a map for list1 to store the value and its index
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < list1.length; i++) {
map.put(list1[i], i);
}
// Step 2: Initialize the minimum index sum to a large value
int minIndexSum = Integer.MAX_VALUE;
List<String> result = new ArrayList<>();
// Step 3: Traverse list2 and find common strings with minimum index sum
for (int j = 0; j < list2.length; j++) {
if (map.containsKey(list2[j])) {
int indexSum = j + map.get(list2[j]);
if (indexSum < minIndexSum) {
result.clear();
result.add(list2[j]);
minIndexSum = indexSum;
} else if (indexSum == minIndexSum) {
result.add(list2[j]);
}
}
}
return result.toArray(new String[result.size()]);
}
public static void main(String[] args) {
Solution sol = new Solution();
String[] list1 = {"Shogun", "Tapioca Express", "Burger King", "KFC"};
String[] list2 = {"Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"};
System.out.println(Arrays.toString(sol.findRestaurant(list1, list2))); // Output: ["Shogun"]
}
}
The time complexity for this solution is (O(n + m)), where (n) is the length of list1
and (m) is the length of list2
. This is because we traverse both lists at most once:
list1
: (O(n))list2
to find the common strings and calculating index sums: (O(m))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?