#2540
Minimum Common Value
EasyArrayHash TableTwo PointersBinary SearchTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using a two-pointer technique leverages the fact that both arrays are sorted. This allows us to efficiently find the smallest common value without unnecessary comparisons.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, one for each array, starting at the beginning.
- 2Step 2: While both pointers are within the bounds of their respective arrays, compare the elements at the pointers.
- 3Step 3: If the elements are equal, return the element as it is the minimum common value.
- 4Step 4: If the element in nums1 is smaller, increment the pointer for nums1; otherwise, increment the pointer for nums2.
- 5Step 5: If the loop ends without finding a common element, return -1.
solution.py12 lines
1# Full working Python code
2
3def min_common_value(nums1, nums2):
4 i, j = 0, 0
5 while i < len(nums1) and j < len(nums2):
6 if nums1[i] == nums2[j]:
7 return nums1[i]
8 elif nums1[i] < nums2[j]:
9 i += 1
10 else:
11 j += 1
12 return -1ℹ
Complexity note: The time complexity is O(n) because we are traversing each array at most once. The space complexity is O(1) since we are using a constant amount of extra space.
- 1Both arrays are sorted, which allows for efficient searching techniques.
- 2Using two pointers minimizes unnecessary comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.