Minimum Index Sum of Common Elements Problem
#3682
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3682.
You are given two integer arrays nums1 and nums2 of equal length n.
We define a pair of indices (i, j) as a good pair if nums1[i] == nums2[j].
Return the minimum index sum i + j among all possible good pairs. If no such pairs exist, return -1.
Example 1:
Input: nums1 = [3,2,1], nums2 = [1,3,1]
Output: 1
Explanation:
- Common elements between nums1 and nums2 are 1 and 3.
- For 3, [i, j] = [0, 1], giving an index sum of i + j = 1.
- For 1, [i, j] = [2, 0], giving an index sum of i + j = 2.
- The minimum index sum is 1.
Example 2:
Input: nums1 = [5,1,2], nums2 = [2,1,3]
Output: 2
Explanation:
- Common elements between nums1 and nums2 are 1 and 2.
- For 1, [i, j] = [1, 1], giving an index sum of i + j = 2.
- For 2, [i, j] = [2, 0], giving an index sum of i + j = 2.
- The minimum index sum is 2.
Example 3:
Input: nums1 = [6,4], nums2 = [7,8]
Output: -1
Explanation:
- Since no common elements between nums1 and nums2, the output is -1.
Constraints:
1 <= nums1.length == nums2.length <= 10^5-10^5 <= nums1[i], nums2[i] <= 10^5
Solution
Approach: Hash Map
For each value, only its first occurrence in nums2 matters, because a later index would only make the sum larger. Store the first index of each value of nums2 in a hash map.
Then walk through nums1. For each nums1[i] found in the map, the index sum is i + first[nums1[i]]; keep the smallest one. If no value is common, return -1.
Complexity: O(n) time and O(n) extra space, where n is the length of each array.
class Solution:
def minimumSum(self, nums1: List[int], nums2: List[int]) -> int:
d = {}
for i, x in enumerate(nums2):
if x not in d:
d[x] = i
ans = float("inf")
for i, x in enumerate(nums1):
if x in d:
ans = min(ans, i + d[x])
return -1 if ans == float("inf") else ans