Minimum Index Sum of Two Lists — LeetCode 599 Python Solution

EasyArrayHash TableString
Problem
#599
Pattern
Hash Map
Reading time
3 min

The 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.

Example

Input
list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
Output
["Shogun"]
Explanation
The only common string is "Shogun".

Python solution

Python
class Solution:
    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
        d = {s: i for i, s in enumerate(list2)}
        ans = []
        mi = inf
        for i, s in enumerate(list1):
            if s in d:
                j = d[s]
                if i + j < mi:
                    mi = i + j
                    ans = [s]
                elif i + j == mi:
                    ans.append(s)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 599. Minimum Index Sum of Two Lists is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 599. Minimum Index Sum of Two Lists?
LeetCode 599. Minimum Index Sum of Two Lists is rated Easy on LeetCode.
What is the time complexity of LeetCode 599. Minimum Index Sum of Two Lists?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 599. Minimum Index Sum of Two Lists?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 599. Minimum Index Sum of Two Lists cover?
LeetCode 599. Minimum Index Sum of Two Lists is tagged Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview