Leetcode 2540. 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.
nums1 and nums2 can be up to 10^5.nums1 and nums2 can range from 1 to 10^9.-1 if there is no common value.Considering that both arrays are sorted, we can efficiently find the minimum common value using a two-pointer technique.
nums1 and nums2.nums1 is smaller, increment the pointer in nums1 to try and find a larger element that might match the current element in nums2.nums2 is smaller, increment the pointer in nums2 to try and find a larger element that might match the current element in nums1.-1.O(m + n), where m is the length of nums1 and n is the length of nums2. This is because each element in both nums1 and nums2 is processed at most once.Here’s the Java implementation of the solution:
public class MinimumCommonValue {
public int getCommon(int[] nums1, int[] nums2) {
int pointer1 = 0;
int pointer2 = 0;
while (pointer1 < nums1.length && pointer2 < nums2.length) {
if (nums1[index1] == nums2[index2]) {
return nums1[index1];
} else if (nums1[index1] < nums2[index2]) {
pointer1++;
} else {
pointer2++;
}
}
return -1; // No common element found
}
public static void main(String[] args) {
MinimumCommonValue sol = new MinimumCommonValue();
int[] nums1 = {1, 2, 3, 4, 5};
int[] nums2 = {3, 5, 7, 9};
System.out.println(sol.getCommon(nums1, nums2)); // Output: 3
int[] nums1_2 = {6, 7, 8, 9};
int[] nums2_2 = {1, 2, 3, 10};
System.out.println(sol.getCommon(nums1_2, nums2_2)); // Output: -1
}
}
This code defines a method getCommon which implements the above strategy using two pointers to find the minimum common value or determine that no common element exists. The main method provides some sample inputs to test the function.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?