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
Two Librarians Finding Common Books๐Ÿ‘จLibrarian A123๐Ÿ‘ฉLibrarian B24Algorithm Steps1Compare: Book 1 vs Book 21 < 2, so A moves to next book2Compare: Book 2 vs Book 2Match found! Return 2๐ŸŽฏ First Common Book: ID 2Time: O(n+m) | Space: O(1)
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.
Asked in
Google 45 Amazon 38 Meta 29 Microsoft 22
72.3K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen