Minimum Common Value — LeetCode 2540 Python Solution

EasyArrayHash TableTwo PointersBinary Search
Problem
#2540
Reading time
2 min

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 -1

Complexity

MeasureComplexity
TimeO(m + n), where m and n are the lengths of the two arrays respectively
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview