Minimum Common Value - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,2,3], nums2 = [2,4]
Output: 2
💡 Note: The smallest element common to both arrays is 2, so we return 2.
Example 2 — No Common Elements
$ Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5]
Output: 2
💡 Note: Common elements are 2 and 3. The minimum is 2.
Example 3 — No Common Elements
$ Input: nums1 = [1,2,3], nums2 = [4,5,6]
Output: -1
💡 Note: No elements are common to both arrays, so 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
Minimum Common Value Hash Map - Store First Array Approach INPUT nums1 (sorted) 1 2 3 nums2 (sorted) 2 4 Input Values: nums1 = [1, 2, 3] nums2 = [2, 4] Find minimum common integer in both arrays ALGORITHM STEPS 1 Create HashSet Initialize empty set 2 Store nums1 Add all nums1 to set HashSet: 1 2 3 3 Scan nums2 Check each element Check 2: set.contains(2)? YES - Found match! 4 Return First Match Return 2 (minimum) FINAL RESULT Common elements found: nums1 nums2 2 Output: 2 OK - Found! Minimum common = 2 Time: O(n + m) Space: O(n) Key Insight: Using a HashSet to store nums1 elements enables O(1) lookup time when scanning nums2. Since nums2 is sorted, the first match found is guaranteed to be the minimum common value. Alternative: Two-pointer approach works since both arrays are sorted (O(n+m) time, O(1) space). TutorialsPoint - Minimum Common Value | Hash Map Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.5K Views
Medium Frequency
~10 min Avg. Time
890 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