Minimum Common Value - Problem
You're tasked with finding the smallest integer that appears in both of two sorted arrays. Think of it as finding the minimum overlap between two ordered lists.
Given two integer arrays nums1 and nums2, both sorted in non-decreasing order, return the minimum integer that exists in both arrays. If no such common integer exists, return -1.
Key Points:
- Both arrays are already sorted (this is a huge hint!)
- We want the smallest common value, not just any common value
- An integer is considered common if it appears at least once in each array
Example: If nums1 = [1,2,3] and nums2 = [2,4], the answer is 2 since it's the only (and therefore minimum) common value.
Input & Output
example_1.py โ Basic Case
$
Input:
nums1 = [1,2,3], nums2 = [2,4]
โบ
Output:
2
๐ก Note:
The smallest integer common to both arrays is 2, since it appears in both nums1 and nums2.
example_2.py โ Multiple Common Elements
$
Input:
nums1 = [1,2,3,6], nums2 = [2,3,4,5]
โบ
Output:
2
๐ก Note:
Both 2 and 3 are common to both arrays, but 2 is smaller, so we return 2.
example_3.py โ No Common Elements
$
Input:
nums1 = [1,3,5], nums2 = [2,4,6]
โบ
Output:
-1
๐ก Note:
There are no integers common to both arrays, so we return -1.
Constraints
- 1 โค nums1.length, nums2.length โค 105
- 1 โค nums1[i], nums2[j] โค 109
- Both nums1 and nums2 are sorted in non-decreasing order
Visualization
Tap to expand
Understanding the Visualization
1
Start at the beginning
Both librarians point to their first (smallest) book ID
2
Compare current books
If IDs match, they found a common book! If not, whoever has the smaller ID moves to their next book
3
Continue until match
Keep comparing and advancing until they find a common book or run out of books
Key Takeaway
๐ฏ Key Insight: By leveraging the sorted property and using two pointers, we can find the minimum common element in a single pass through both arrays, making this the most efficient solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code