Minimum Common Value — LeetCode 2540 Python Solution
EasyArrayHash TableTwo PointersBinary Search
- Problem
- #2540
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums1 = [1,2,3], nums2 = [2,4]
- Output
- 2
- Explanation
- The smallest element common to both arrays is 2, so we return 2.
Python solution
Python
class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
i = j = 0
m, n = len(nums1), len(nums2)
while i < m and j < n:
if nums1[i] == nums2[j]:
return nums1[i]
if nums1[i] < nums2[j]:
i += 1
else:
j += 1
return -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(m + n), where m and n are the lengths of the two arrays respectively |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 2540. Minimum Common Value is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2540. Minimum Common Value?
- LeetCode 2540. Minimum Common Value is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2540. Minimum Common Value?
- The Python solution on this page runs in O(m + n), where m and n are the lengths of the two arrays respectively.
- What is the space complexity of LeetCode 2540. Minimum Common Value?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2540. Minimum Common Value cover?
- LeetCode 2540. Minimum Common Value is tagged Array, Hash Table, Two Pointers and Binary Search on LeetCode.