Sponsored
Sponsored
This approach utilizes the fact that both arrays are sorted. Using two pointers, one for each array, we traverse the arrays to find the smallest common value:
Time Complexity: O(n + m), where n and m are the lengths of the two arrays. We only traverse each array once.
Space Complexity: O(1), no additional space is used apart from a few variables.
1public class Main {
2 public static int findMinCommonValue(int[] nums1, int[] nums2) {
3 int i = 0, j = 0;
4 while (i < nums1.length && j < nums2.length) {
5 if (nums1[i] == nums2[j]) {
6 return nums1[i];
7 } else if (nums1[i] < nums2[j]) {
8 i++;
9 } else {
10 j++;
11 }
12 }
13 return -1;
14 }
15
16 public static void main(String[] args) {
17 int[] nums1 = {1, 2, 3};
18 int[] nums2 = {2, 4};
19 System.out.println(findMinCommonValue(nums1, nums2));
20 }
21}
The Java version also utilizes the same two-pointer strategy. It keeps the code elegant with the use of simple while-loop control structures as seen in other popular languages.
This approach uses a HashSet to store the elements of the smaller array, providing a quick way to check for common elements:
Time Complexity: O(n log n + m), mainly due to qsort and possibly bsearch in the worst case scenario per element in the second array.
Space Complexity: O(n), additional space used for sorting elements.
This C solution uses a combination of manual sorting and binary searching with the help of C's standard library functions to find a common minimum element. The input is checked, potentially swapped for size optimization, then sorted and binary searched for elements presence.