Minimum Index Sum of Two Lists

Given two arrays of strings list1 and list2, find the common strings with the least index sum. A common string is a string that appears in both list1 and list2. If it appears at list1[i] and list2[j], its index sum is i + j, and it has the least index sum if no other common string has a smaller one. Return all the common strings with the least index sum, in any order.

30:00

Minimum Index Sum of Two Lists
easy
Free written solution
Topics
Companies

Given two arrays of strings list1 and list2, find the common strings with the least index sum. A common string is a string that appears in both list1 and list2. If it appears at list1[i] and list2[j], its index sum is i + j, and it has the least index sum if no other common string has a smaller one. Return all the common strings with the least index sum, in any order.

Example 1:
Input: {"list1":["Shogun","Tapioca Express","Burger King","KFC"],"list2":["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]}
Output: ["Shogun"]
Constraints:
  • 1≤list1.length,list2.length≤10001 \leq \text{list1.length}, \text{list2.length} \leq 1000

  • 1≤list1[i].length,list2[i].length≤301 \leq \text{list1}[i].\text{length}, \text{list2}[i].\text{length} \leq 30

  • list1[i]\text{list1}[i] and list2[i]\text{list2}[i] consist of spaces and English letters.

  • All the strings of list1 are unique, and all the strings of list2 are unique.

  • There is at least one common string between list1 and list2.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"list1":["Shogun","Tapioca Express","Burger King","KFC"],"list2":["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]}

Store every list1 string with its position in a hash map (4 entries), so each list2 string can find its partner in O(1).

list1 (in hash map)

0

Shogun

1

Tapioca Express

2

Burger King

3

KFC

list2 (scan)

0

Piatti

1

The Grill at Torrey Pines

2

Hungry Hunter Steakhouse

3

Shogun

current

-

best index sum

∞

answer (0)

empty

Variables
VariableValue
bestinf
j-
DepthFunction Call
Stack empty
0/6