↓Skip to main content
  1. LeetCode/

LeetCode 2540: Minimum Common Value

·2 mins· ·
LeetCode Easy Two-Pointers Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2026-01-31

  • Submissions: Accepted (first try)

Approach
#

Both arrays are sorted. Keep one pointer in each and compare from the smallest:

  • Equal: this is the smallest common value; return it.
  • Not equal: the smaller value cannot appear later in the other array (later values are only larger), so advance the smaller side.

My Solution
#

class Solution:
    def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
        i = j = 0
        while i < len(nums1) and j < len(nums2):
            if nums1[i] == nums2[j]:
                return nums1[i]
            if nums1[i] < nums2[j]:
                i += 1
            else:
                j += 1
        return -1

My original checked “is this already the last element” before advancing and broke out if so. That is unnecessary: once a pointer reaches the end, the while condition stops the loop.

Complexity
#

Time O(n + m), space O(1).

Mistakes to Avoid
#

  • Advancing the larger side: it skips the answer.
  • Intersecting sets and taking the minimum: it works, but uses O(n) space and ignores the sorting.

Interview Explanation
#

Both arrays are sorted, so I compare from the front with two pointers. Equal values give the smallest common value; otherwise the smaller value cannot be found in the other array anymore, so I advance its side. If either side runs out first, I return -1. Time O(n + m), space O(1).

Related

LeetCode 2570: Merge Two 2D Arrays by Summing Values
·2 mins
LeetCode Easy Two-Pointers Array
LeetCode 2570 note: merge two id-sorted arrays with two pointers, adding values when ids match
LeetCode 2200: Find All K-Distant Indices in an Array
·2 mins
LeetCode Easy Two-Pointers Array
LeetCode 2200 note: extend each key k positions both ways, and keep a pointer to how far output has gone so overlapping ranges are not emitted twice
LeetCode 3069: Distribute Elements Into Two Arrays I
·1 min
LeetCode Easy Array Two-Pointers Simulation
LeetCode 3069 note: simulate the rule: the first two go to separate arrays, then each element joins the array whose last element is larger
LeetCode 942: DI String Match
·1 min
LeetCode Easy Array Two-Pointers String Greedy
LeetCode 942 note: two pointers hold the smallest and largest unused values; place the smallest on I and the largest on D
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side