easy Minimum Common Value
Problem Statement
Given two sorted arrays nums1 and nums2 containing integers only, return the smallest integer that appears in both arrays. If there isn't any integer that exists in both arrays, the function should return -1.
Examples
Example 1:
- input: nums1 = [1, 3, 5, 7], nums2 = [3, 4, 5, 6, 8, 10]
- expectedOutput: 3
- Justification: Both arrays share the integers 3 and 5, but the smallest common integer is 3.
Example 2:
- input: nums1 = [2, 4, 6], nums2 = [1, 3, 5]
- expectedOutput: -1
- Justification: There are no integers common to both nums1 and nums2, hence the output is -1.
Example 3:
- input: nums1 = [1, 2, 2, 3], nums2 = [2, 2, 4]
- expectedOutput: 2
- Justification: The integer 2 is the only common number between nums1 and nums2, appearing multiple times in both, and it is the smallest.
Constraints:
- 1 <= nums1.length, nums2.length <= 105
- 1 <= nums1[i], nums2[j] <= 109
- Both nums1 and nums2 are sorted in non-decreasing order.
Try it yourself
Try solving this question here:
✅ Solution Minimum Common Value
Problem Statement
Given two sorted arrays nums1 and nums2 containing integers only, return the smallest integer that appears in both arrays. If there isn't any integer that exists in both arrays, the function should return -1.
Examples
Example 1:
- input: nums1 = [1, 3, 5, 7], nums2 = [3, 4, 5, 6, 8, 10]
- expectedOutput: 3
- Justification: Both arrays share the integers 3 and 5, but the smallest common integer is 3.
Example 2:
- input: nums1 = [2, 4, 6], nums2 = [1, 3, 5]
- expectedOutput: -1
- Justification: There are no integers common to both nums1 and nums2, hence the output is -1.
Example 3:
- input: nums1 = [1, 2, 2, 3], nums2 = [2, 2, 4]
- expectedOutput: 2
- Justification: The integer 2 is the only common number between nums1 and nums2, appearing multiple times in both, and it is the smallest.
Constraints:
- 1 <= nums1.length, nums2.length <= 105
- 1 <= nums1[i], nums2[j] <= 109
- Both nums1 and nums2 are sorted in non-decreasing order.
Solution
To efficiently solve this problem, a binary search algorithm can be employed due to the sorted nature of the input arrays. The binary search approach will be utilized to find the smallest common integer between the two arrays.
We start by iterating through the smaller array and use binary search on the larger array to check for the presence of each element from the smaller array. This ensures that we only search for potential common values and hence minimize the number of comparisons. Using binary search reduces the time complexity significantly compared to a linear search, especially for larger arrays, making this approach both efficient and effective.
Step-by-step Algorithm
-
Swap Arrays if Necessary:
- If
nums1is longer thannums2, swap them. This ensures that the binary search is always performed on the larger array, optimizing search efficiency.
- If
-
Iterate through the Smaller Array:
- Loop through each element
numin the smaller array (nums1).
- Loop through each element
-
Binary Search in Larger Array:
- For each element
num, call thebinarySearchmethod on the larger array (nums2). - If
binarySearchreturnsTrue(element found innums2), immediately return thenumas it is the smallest common element found so far.
- For each element
-
No Common Element Found:
- If the loop completes without finding any common element, return -1.
-
Binary Search Method:
- Initialize two pointers,
leftandright, to define the search boundaries. - While
leftis less than or equal toright:- Calculate the middle index
mid. - Compare the target with the element at
mid. - Adjust the
leftorrightpointers based on the comparison result to narrow the search.
- Calculate the middle index
- If the target is not found by the end of the loop, return
False.
- Initialize two pointers,
Algorithm Walkthrough
Let's consider the input: nums1 = [1, 3, 5, 7], nums2 = [3, 4, 5, 6, 8, 10]
-
Initial Check:
nums1length is 4 andnums2length is 6. No need to swap sincenums2is already larger.
-
Binary Search for
1:- Initialize
left = 0andright = 5. - Calculate the middle index:
mid = (0 + 5) // 2 = 2. The element atmidisnums2[2] = 5. - Since
nums2[2](5) is greater than 1, adjust therightpointer:right = mid - 1 = 1. - Recalculate
mid:mid = (0 + 1) // 2 = 0. The element atmidisnums2[0] = 3. - Since
nums2[0](3) is greater than 1, adjust therightpointer again:right = mid - 1 = -1. - At this point,
left = 0is greater thanright = -1, ending the search. The target1is not found.
- Initialize
-
Binary Search for
3:- Found in
nums2.- Start:
left = 0,right = 5,mid = 2(nums2[2] = 5). nums2[2]> 3, so adjustrighttomid - 1(right = 1).- New
mid = 0(nums2[0] = 3). nums2[0]= 3, found the target. Return3.
- Start:
- Found in
-
Return Value:
- The smallest common element
3is returned after the second binary search.
- The smallest common element
Code
public class Solution {
// Function to find the minimum common value between two arrays
public int findMinimumCommonValue(int[] nums1, int[] nums2) {
// Ensure binary search is done on the larger array
if (nums1.length > nums2.length) {
return findMinimumCommonValue(nums2, nums1);
}
// Search for each element of the smaller array in the larger array
for (int num : nums1) {
if (binarySearch(nums2, num)) {
return num; // Return the common element found
}
}
// If no common elements are found, return -1
return -1;
}
// Binary search method to find if target exists in nums
private boolean binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
// Continue searching while left pointer is less than or equal to right pointer
while (left <= right) {
int mid = left + (right - left) / 2; // Calculate the middle index
if (nums[mid] > target) {
right = mid - 1; // If target is less than element at mid, search left half
} else if (nums[mid] < target) {
left = mid + 1; // If target is greater than element at mid, search right half
} else {
return true; // Target found
}
}
return false; // Target not found
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test cases
System.out.println(
solution.findMinimumCommonValue(
new int[] { 1, 3, 5, 7 },
new int[] { 3, 4, 5, 6, 8, 10 }
)
); // Expected Output: 3
System.out.println(
solution.findMinimumCommonValue(
new int[] { 2, 4, 6 },
new int[] { 1, 3, 5 }
)
); // Expected Output: -1
System.out.println(
solution.findMinimumCommonValue(
new int[] { 1, 2, 2, 3 },
new int[] { 2, 2, 4 }
)
); // Expected Output: 2
}
}
Complexity Analysis
- Time Complexity:
- The major time-consuming operation in this solution is the binary search performed on the larger array for each element of the smaller array.
- Since binary search operates in
time, where (m) is the length of the larger array, and assuming (n) is the length of the smaller array, the overall time complexity becomes .
- Space Complexity:
- The space complexity of the solution is
, as the solution only uses a constant amount of extra space for pointers and temporary variables regardless of the input size.
- The space complexity of the solution is
🤖 Don't fully get this? Learn it with Claude
Stuck on Minimum Common Value? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Minimum Common Value** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Minimum Common Value** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Minimum Common Value**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Minimum Common Value**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.