2540. Minimum Common Value LeetCode Solution

In this guide, you will get 2540. Minimum Common Value LeetCode Solution with the best time and space complexity. The solution to Minimum Common Value problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Minimum Common Value solution in C++
  4. Minimum Common Value solution in Java
  5. Minimum Common Value solution in Python
  6. Additional Resources
2540. Minimum Common Value LeetCode Solution image

Problem Statement of Minimum Common Value

Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the minimum integer common to both arrays. If there is no common integer amongst nums1 and nums2, return -1.
Note that 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.

Constraints:

1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[j] <= 109
Both nums1 and nums2 are sorted in non-decreasing order.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

2540. Minimum Common Value LeetCode Solution in C++

class Solution {
 public:
  int getCommon(vector<int>& nums1, vector<int>& nums2) {
    int i = 0;  // nums1's index
    int j = 0;  // nums2's index

    while (i < nums1.size() && j < nums2.size()) {
      if (nums1[i] == nums2[j])
        return nums1[i];
      if (nums1[i] < nums2[j])
        ++i;
      else
        ++j;
    }

    return -1;
  }
};
/* code provided by PROGIEZ */

2540. Minimum Common Value LeetCode Solution in Java

class Solution {
  public int getCommon(int[] nums1, int[] nums2) {
    int i = 0; // nums1's index
    int j = 0; // nums2's index

    while (i < nums1.length && j < nums1.length) {
      if (nums1[i] == nums2[j])
        return nums1[i];
      if (nums1[i] < nums2[j])
        ++i;
      else
        ++j;
    }

    return -1;
  }
}
// code provided by PROGIEZ

2540. Minimum Common Value LeetCode Solution in Python

class Solution:
  def getCommon(self, nums1: list[int], nums2: list[int]) -> int:
    i = 0  # nums1's index
    j = 0  # nums2's index

    while i < len(nums1) and j < len(nums2):
      if nums1[i] == nums2[j]:
        return nums1[i]
      if nums1[i] < nums2[j]:
        i += 1
      else:
        j += 1

    return -1
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.