Leetcode 2540: Minimum Common Value

grid47
grid47
Exploring patterns and algorithms
Feb 27, 2024 5 min read

Given two integer arrays nums1 and nums2 sorted in non-decreasing order, return the smallest integer that is common to both arrays. If no such integer exists, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of two integer arrays `nums1` and `nums2`, both sorted in non-decreasing order.
Example: nums1 = [10, 15, 20], nums2 = [5, 10, 25]
Constraints:
• 1 <= nums1.length, nums2.length <= 10^5
• 1 <= nums1[i], nums2[j] <= 10^9
Output: The output should be the smallest integer common to both arrays. If no common integer exists, return `-1`.
Example: 10
Constraints:
• The result should be an integer or -1 if no common integer exists.
Goal: To find the smallest integer that is common in both arrays.
Steps:
• Initialize two pointers to traverse the arrays.
• Compare elements of both arrays at the current positions of the pointers.
• If the elements match, return the common element as the result.
• If the element in the first array is smaller, increment the pointer for the first array.
• If the element in the second array is smaller, increment the pointer for the second array.
• If no common elements are found, return -1.
Goal: Ensure that the solution efficiently handles arrays with lengths up to 10^5 and values as large as 10^9.
Steps:
• Both arrays are sorted in non-decreasing order.
• The solution should be efficient in terms of time and space.
Assumptions:
• Both arrays `nums1` and `nums2` are valid and sorted in non-decreasing order.
• The arrays may contain duplicates.
Input: [4, 7, 9], [5, 7, 8]
Explanation: The smallest common element between both arrays is 7, so the output is 7.

Input: [10, 15, 20], [5, 10, 25]
Explanation: The smallest common element between both arrays is 10, so the output is 10.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus