Minimum Common Value

Gulshan KumarGulshan Kumar
1 min read

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.

LeetCode Problem - 2540

class Solution {
    // This method finds the first common element between two arrays `nums1` and `nums2`.
    public int getCommon(int[] nums1, int[] nums2) {
        // HashSet to store unique elements from nums1
        HashSet<Integer> hs1 = new HashSet<>();
        // Add all elements from nums1 to the HashSet
        for (int e : nums1) {
            hs1.add(e);
        }

        // Variable to store the common element found
        int result = -1;

        // Iterate through each element in nums2
        for (int j : nums2) {
            // If the current element exists in nums1 HashSet, it is common
            if (hs1.contains(j)) {
                result = j;
                break;
            }
        }
        // Return the first common element found, or -1 if none exists
        return result;
    }
}
0
Subscribe to my newsletter

Read articles from Gulshan Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gulshan Kumar
Gulshan Kumar

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman. I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.