Minimum Common Value

Minimum Common Value

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.

LeetCode Problem - 2540

class Solution {
    // This method finds the first common element between two arrays `nums1` and `nums2`.
    public int getCommon(int[] nums1, int[] nums2) {
        // HashSet to store unique elements from nums1
        HashSet<Integer> hs1 = new HashSet<>();
        // Add all elements from nums1 to the HashSet
        for (int e : nums1) {
            hs1.add(e);
        }

        // Variable to store the common element found
        int result = -1;

        // Iterate through each element in nums2
        for (int j : nums2) {
            // If the current element exists in nums1 HashSet, it is common
            if (hs1.contains(j)) {
                result = j;
                break;
            }
        }
        // Return the first common element found, or -1 if none exists
        return result;
    }
}