1 minute read

2540. Minimum Common Value

Difficulty: Easy

Related Topics: Array, Hash Table, Two Pointers, Binary Search

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.

First Attempt:

Code:

class Solution:
    def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
        common = []
        for i in nums1:
            if i in nums2:
                return i

Feedbacks:

I first simply just implemented for loop and if statement to find the least common value. Time complexity = O(n^2), but it returned back with time limit exceed error. So I decided to use binary search which has time complexity of O(log n) to reduce the running time.

Second Attempt:

Code:

class Solution:
    def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
        def binary(target):
            l=0
            r=len(nums1)-1
            while l<=r:
                mid = (l+r)//2
                if nums2[mid] == target:
                    return target
                elif nums2[mid] > target:
                    r = mid-1
                else:
                    l = mid+1

        if len(nums1) < 15 and len(nums2) < 15:
            for i in nums1:
                if i in nums2:
                    return i
            return -1
        else:
            count=0
            for i in nums1:
                a = binary(i)
                print(a)
                if a:
                    return a
                else:
                    count+=1
            if count == len(nums1):
                return -1

Feedbacks:

As I decided to use binary search, I made a function of common binary search, and through the for loop, I applied function to every elements, so time complexity of this code will be O(n logn) and it successfully solved the problem. But while I was looking for other solutions, I found two pointers could also be used for this problem very efficiently.