Leetcode 2540. Minimum Common Value
You are given two integer arrays nums1
and nums2
sorted in non-decreasing order. There is exactly one integer that is common in both arrays. Return this integer. You must write an algorithm with O(log n) runtime complexity.
nums1
and nums2
is within the range [1, 10^4] and the values of elements are within a certain range of integers.Since we need to achieve an O(log n) runtime complexity, a binary search approach is suitable here. One effective way of solving this problem involves using the fact that both arrays are sorted:
nums1
.nums1
, perform a binary search in nums2
to see if that element exists in nums2
.This approach ensures that we are leveraging the O(log n) property of binary search.
#include <vector>
#include <algorithm>
class Solution {
public:
int getCommon(std::vector<int>& nums1, std::vector<int>& nums2) {
for(int num : nums1) {
if (binarySearch(nums2, num)) {
return num;
}
}
return -1; // Based on problem constraints this should never happen.
}
private:
bool binarySearch(const std::vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return true;
}
else if (nums[mid] < target) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return false;
}
};
nums1
): O(m), where m
is the length of nums1
.nums2
for each element of nums1
: O(log n), where n
is the length of nums2
.Combining both, the overall time complexity is:
This satisfies the requirement of achieving a logarithmic runtime since one array is traversed linearly while the other is searched logarithmically.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?