LeetCode 2540: Minimum Common Value

Problem Description

Explanation

To find the minimum common value between two sorted arrays, we can use a two-pointer approach. We will iterate through both arrays simultaneously using two pointers, incrementing the pointer for the smaller value at each step. If we find a common value, we update the minimum common value found so far. This approach ensures that we find the minimum common value as we are iterating over sorted arrays.

  • Start with two pointers at the beginning of both arrays.
  • Move the pointer of the smaller value to the next element.
  • If the values pointed to are equal, update the minimum common value found.
  • Repeat until the end of either array is reached.

Time complexity: O(m + n) where m and n are the lengths of the input arrays nums1 and nums2 respectively. Space complexity: O(1)

Solutions

class Solution {
    public int findMinimumCommonValue(int[] nums1, int[] nums2) {
        int i = 0, j = 0;
        int minCommon = Integer.MAX_VALUE;

        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] == nums2[j]) {
                minCommon = Math.min(minCommon, nums1[i]);
                i++;
                j++;
            } else if (nums1[i] < nums2[j]) {
                i++;
            } else {
                j++;
            }
        }

        return minCommon == Integer.MAX_VALUE ? -1 : minCommon;
    }
}

Loading editor...