Here, we will see how to solve Minimum Common Value Solution of leet code 2540 problem.
You are given Given two integer arrays nums1
and nums2
, sorted in non-decreasing order. You have to return the minimum integer common to both arrays. If there is no common integer amongst nums1
and nums2
then return -1
.
Note: An integer is said to be common to nums1
and nums2
if both arrays have at least one occurrence of that integer.
Example 1:
Input: nums1 = [1,2,3], nums2 = [2,4] Output: 2 Explanation: The smallest element common to both arrays is 2, so we return 2.
Example 2:
Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5] Output: 2 Explanation: There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.
Approach:
- Iterate both the arrays from left to right.
- If the number is equal in nums1 and nums2 then return that number
- If the number is not equal and nums1’s number is less than nums2’s number in iterator then increment iterator of nums1.
- If the number is not equal and nums1’s number is greater than nums2’s number in iterator then increment iterator of nums2.
Minimum Common Value Solution in C++ and go:
Here, we will be solving problem in multiple ways with code.
C++ code 1:
class Solution { public: int getCommon(vector<int>& nums1, vector<int>& nums2) { int len1 = nums1.size() - 1, i = 0; int len2 = nums2.size() - 1, j = 0; while(i <= len1 && j <= len2) { if(nums1[i] == nums2[j]) { return nums1[i]; } else if(nums1[i] < nums2[j]) { i++; } else { j++; } } return -1; } };
Go code 1:
func getCommon(nums1 []int, nums2 []int) int { var len1, i = len(nums1) - 1, 0 var len2, j = len(nums2) - 1, 0 for i <= len1 && j <= len2 { if nums1[i] == nums2[j] { return nums1[i] } else if nums1[i] < nums2[j] { i++ } else { j++ } } return -1; }
Output:
Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5]
Output: 2
Time complexity: O(n)
Space complexity: O(1)
To check more leetcode problem’s solution. Pls click given below link:
https://techieindoor.com/category/leetcode/
https://techieindoor.com/category/interview-questions/