2540. Minimum Common Value

Updated: 2024-03-12
1 min read
[]

On This Page

LeetCode problem 2540

By initializing two pointers, one for each array, we can compare the elements they point to. If the elements are equal, we’ve found a common value. If not, we move the pointer pointing to the smaller value forward. This approach ensures that we only traverse each array once.

class Solution:
    def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
        i = 0
        j = 0
        N1 = len(nums1)
        N2 = len(nums2)
        while i < N1 and j < N2:
            if nums1[i] == nums2[j]:
                return nums1[i]
            if nums1[i] < nums2[j]:
                i += 1
            else:
                j += 1
        return -1