Minimum Common Value - LeetCode Daily Challenge
Problem Statement
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.
Try here before watching the video.
Video Explanation
This problem can also be solved using Binary Search, but it is not only efficient one. Binary Search is more suitable if one of the arrays is having very small size as compared to the other one. Or we can say:
if((N + M) > (N * log M)) {
Apply Binary Search on M size array for every element present in N size array.
} else {
Apply Two Pointers
}
Java Code
class Solution {
public int getCommon(int[] nums1, int[] nums2) {
int i = 0, j = 0;
while(i < nums1.length && j < nums2.length) {
if(nums1[i] == nums2[j]) {
return nums1[i];
} else if(nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
return -1;
}
}
C++ Code
class Solution {
public:
int getCommon(vector<int>& nums1, vector<int>& nums2) {
int i = 0, j = 0;
while(i < nums1.size() && j < nums2.size()) {
if(nums1[i] == nums2[j]) {
return nums1[i];
} else if(nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
return -1;
}
};
Python Code
class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums1[i] == nums2[j]:
return nums1[i]
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return -1
Javascript Code
var getCommon = function(nums1, nums2) {
let i = 0, j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] === nums2[j]) {
return nums1[i];
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
return -1;
};
Go Code
func getCommon(nums1 []int, nums2 []int) int {
i, j := 0, 0
for i < len(nums1) && j < len(nums2) {
if nums1[i] == nums2[j] {
return nums1[i]
} else if nums1[i] < nums2[j] {
i++
} else {
j++
}
}
return -1
}
Complexity Analysis
Time Complexity: O(N + M), we are iterating through both the arrays.
Space Complexity: O(1), we are not taking any extra space.