LeetCode 599: Minimum Index Sum of Two Lists Solution

Master LeetCode problem 599 (Minimum Index Sum of Two Lists), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

599. Minimum Index Sum of Two Lists

Problem Explanation

Explanation

To solve this problem, we can iterate through both lists and keep track of the index sum for each common string found. We maintain a hashmap to store the indices of strings in list1. While iterating through list2, if we find a common string, we calculate the index sum and update our result accordingly. If we find a common string with a smaller index sum, we clear the result list and add the new string.

  • Let m be the length of list1 and n be the length of list2.
  • Time complexity is O(m + n) as we iterate through both lists.
  • Space complexity is O(m) to store the indices of strings in list1.

Solution Code

import java.util.*;

class Solution {
    public String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> map = new HashMap<>();
        List<String> result = new ArrayList<>();
        int minSum = Integer.MAX_VALUE;

        for (int i = 0; i < list1.length; i++) {
            map.put(list1[i], i);
        }

        for (int j = 0; j < list2.length; j++) {
            if (map.containsKey(list2[j])) {
                int indexSum = j + map.get(list2[j]);
                if (indexSum < minSum) {
                    result.clear();
                    result.add(list2[j]);
                    minSum = indexSum;
                } else if (indexSum == minSum) {
                    result.add(list2[j]);
                }
            }
        }

        return result.toArray(new String[result.size()]);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 599 (Minimum Index Sum of Two Lists)?

This page provides optimized solutions for LeetCode problem 599 (Minimum Index Sum of Two Lists) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 599 (Minimum Index Sum of Two Lists)?

The time complexity for LeetCode 599 (Minimum Index Sum of Two Lists) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 599 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 599 in Java, C++, or Python.

Back to LeetCode Solutions