Description
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 <= 1051 <= nums1[i], nums2[j] <= 109- Both
nums1andnums2are sorted in non-decreasing order.
Solutions
This solution applies the same two-pointer strategy with variables pos1 and pos2 to traverse both sorted arrays in parallel. It compares elements at the current positions and returns the match immediately upon finding one, avoiding an unnecessary comparison in the next iteration. By advancing the pointer pointing to the smaller element, it efficiently narrows the search space, achieving O(n + m) time complexity with O(1) extra space and returning -1 when no common element is found.
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var getCommon = function(nums1, nums2) {
let pos1 = 0;
let pos2 = 0;
while (pos1 < nums1.length && pos2 < nums2.length) {
if (nums1[pos1] === nums2[pos2]) return nums1[pos1];
if (nums1[pos1] < nums2[pos2]) {
pos1++;
} else {
pos2++;
}
}
return -1;
};