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.
1function findMinCommonValue(nums1, nums2) {
2 let i = 0, j = 0;
3 while (i < nums1.length && j < nums2.length) {
4 if (nums1[i] === nums2[j]) {
5 return nums1[i];
6 } else if (nums1[i] < nums2[j]) {
7 i++;
8 } else {
9 j++;
10 }
11 }
12 return -1;
13}
14
15const nums1 = [1, 2, 3];
16const nums2 = [2, 4];
17console.log(findMinCommonValue(nums1, nums2));
In JavaScript, the two-pointer technique is applied just like in other implementations. It makes effective use of simple array operations and control flow to ensure the time complexity remains efficient.
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.