Minimum Common Value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
# Step 1: Initialize two pointers, one for each array
pointer1 = 0
pointer2 = 0
# Step 2: While neither pointer has reached the end of its array
while pointer1 < len(nums1) and pointer2 < len(nums2):
# If the elements at the pointers are equal, this is the smallest common integer
if nums1[pointer1] == nums2[pointer2]:
return nums1[pointer1]
# If the element in nums1 is smaller, increment the pointer for nums1
elif nums1[pointer1] < nums2[pointer2]:
pointer1 += 1
# If the element in nums2 is smaller, increment the pointer for nums2
else:
pointer2 += 1
# Step 3: If the loop completes without returning, there is no common integer
return -1
|
This function uses a two-pointer approach to find the smallest common integer. Each pointer traverses its respective sorted array. If the elements at the pointers are equal, that’s the smallest common integer. If one element is smaller than the other, we move the pointer for the smaller element. If we traverse both arrays without finding a common integer, we return -1.