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.
1def find_min_common_value(nums1, nums2):
2 i, j = 0, 0
3 while i < len(nums1) and j < len(nums2):
Using Python's list indexing and a simple while-loop structure similar to other languages, this solution finds the minimum common element using the two-pointer technique efficiently.
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.
#include <vector>
#include <unordered_set>
int findMinCommonValue(const std::vector<int>& nums1, const std::vector<int>& nums2) {
std::unordered_set<int> set(nums1.begin(), nums1.end());
for (int num : nums2) {
if (set.find(num) != set.end()) {
return num;
}
}
return -1;
}
int main() {
std::vector<int> nums1 = {1, 2, 3};
std::vector<int> nums2 = {2, 4};
std::cout << findMinCommonValue(nums1, nums2) << std::endl;
return 0;
}
In this C++ implementation, we use an unordered_set to store all elements from the smaller array for constant-time lookup. We then iterate over the second array to check directly for the presence of elements in the set.