322. Minimum Index Sum of Two Lists

Easy
Indexed Lookup
Hashing

Problem

Given two arrays of unique strings list1 and list2, find all common strings whose index sum is the smallest among all common strings. Return the answer in any order.

Examples

Example 1

Input: ["Shogun","Tapioca Express","Burger King","KFC"], ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
Output: ["Shogun"]

Example 2

Input: ["Shogun","Tapioca Express","Burger King","KFC"], ["KFC","Shogun","Burger King"]
Output: ["Shogun"]

Example 3

Input: ["happy","sad","good"], ["sad","happy","good"]
Output: ["happy","sad"]
Constraints

1 <= list1.length, list2.length <= 1000

Every list contains unique strings.

At least one common string exists.

Hints

?? Map every string in the first list to its index.

?? Scan the second list and compute index sums only for common strings.

?? Maintain the smallest sum found so far.

Expected Complexity
Time: O(n + m)
Space: O(n)
Follow-up

Can you stop scanning early under any useful ordering condition?

Practice Notes

Attempts: 0

Time spent: 0min

Hints used: 0

00:00
Loading...
Case 1
Case 2
Case 3
Input
["Shogun","Tapioca Express","Burger King","KFC"], ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
Expected
["Shogun"]