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.
1using System;
2
3public class Program
4{
5 public static int FindMinCommonValue(int[] nums1, int[] nums2)
6 {
7 int i = 0, j = 0;
8 while (i < nums1.Length && j < nums2.Length)
9 {
10 if (nums1[i] == nums2[j])
11 {
12 return nums1[i];
13 }
14 else if (nums1[i] < nums2[j])
{
i++;
}
else
{
j++;
}
}
return -1;
}
public static void Main()
{
int[] nums1 = {1, 2, 3};
int[] nums2 = {2, 4};
Console.WriteLine(FindMinCommonValue(nums1, nums2));
}
}
This C# solution similarly utilizes the two-pointer approach to find the smallest common value. It's concise and efficient, iterating over the integer arrays using simple control structures.
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.
The JavaScript solution leverages the Set object for fast membership checks. Elements from one list are inserted into a Set and checked against the second list for common occurrence.