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.
1#include <stdio.h>
2
3int findMinCommonValue(int *nums1, int nums1Size, int *nums2, int nums2Size) {
4 int i = 0, j = 0;
5 while (i < nums1Size && j < nums2Size) {
6 if (nums1[i] == nums2[j]) {
7 return nums1[i];
8 } else if (nums1[i] < nums2[j]) {
9 i++;
10 } else {
11 j++;
12 }
13 }
14 return -1;
15}
16
17int main() {
18 int nums1[] = {1, 2, 3};
19 int nums2[] = {2, 4};
20 int result = findMinCommonValue(nums1, 3, nums2, 2);
21 printf("%d\n", result);
22 return 0;
23}
This code uses a two-pointer technique to find the minimum common value. It initializes two pointers at the beginning of both arrays and progresses them based on the comparison of the elements they point to. If an equal element is found on both sides, it is the smallest common element due to sorted nature of arrays, and thus it is returned. If no common element is found until any one pointer reaches the end, -1 is returned.
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.