Minimum Common Value

easy two pointers binary search array

Problem

You are given two integer arrays, each sorted in non-decreasing order. Return the smallest integer that appears in both arrays. If the two arrays share no common value, return -1.

Inputnums1 = [1, 2, 3], nums2 = [2, 4]
Output2
The only value present in both arrays is 2, so it is the minimum common value. (3 is in nums1 only, 4 is in nums2 only.)

def get_common(nums1, nums2):
    i, j = 0, 0
    while i < len(nums1) and j < len(nums2):
        if nums1[i] == nums2[j]:
            return nums1[i]
        if nums1[i] < nums2[j]:
            i += 1
        else:
            j += 1
    return -1
function getCommon(nums1, nums2) {
  let i = 0, j = 0;
  while (i < nums1.length && j < nums2.length) {
    if (nums1[i] === nums2[j]) return nums1[i];
    if (nums1[i] < nums2[j]) i++;
    else j++;
  }
  return -1;
}
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];
            if (nums1[i] < nums2[j]) i++;
            else j++;
        }
        return -1;
    }
}
int getCommon(vector<int>& nums1, vector<int>& nums2) {
    int i = 0, j = 0;
    while (i < (int)nums1.size() && j < (int)nums2.size()) {
        if (nums1[i] == nums2[j]) return nums1[i];
        if (nums1[i] < nums2[j]) i++;
        else j++;
    }
    return -1;
}
Time: O(n + m) Space: O(1)