Minimum Common Value Problem
#2540
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 2540.
Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the minimum integer common to both arrays. If there is no common integer amongst nums1 and nums2, return -1.
Note that an integer is said to be common to nums1 and nums2 if both arrays have at least one occurrence of that integer.
Example 1:
Input: nums1 = [1,2,3], nums2 = [2,4]
Output: 2
Explanation: The smallest element common to both arrays is 2, so we return 2.
Example 2:
Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5]
Output: 2
Explanation: There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.
Constraints:
1 <= nums1.length, nums2.length <= 10^51 <= nums1[i], nums2[j] <= 10^9- Both
nums1andnums2are sorted in non-decreasing order.
Solution
Approach: Two Pointers
Both arrays are sorted, so walk one pointer through each. If the two values are equal, that is the smallest common value. Otherwise the smaller value cannot appear in the other array any more, so advance the pointer at the smaller value. If a pointer runs off the end, there is no common value and the answer is -1.
Complexity: O(m + n) time and O(1) extra space.
class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
i = j = 0
m, n = len(nums1), len(nums2)
while i < m and j < n:
if nums1[i] == nums2[j]:
return nums1[i]
if nums1[i] < nums2[j]:
i += 1
else:
j += 1
return -1