LeetCode Entry

2540. Minimum Common Value

09.03.2024 easy 2024 kotlin rust

First common number in two sorted arrays

2540. Minimum Common Value easy blog post substack youtube image.png

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/533

Problem TLDR

First common number in two sorted arrays #easy

Intuition

There is a short solution with Set and more optimal with two pointers: move the lowest one.

Approach

Let’s implement both of them.

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\), or O(n) for Set solution

Code


  fun getCommon(nums1: IntArray, nums2: IntArray) = nums1
    .toSet().let { s -> nums2.firstOrNull { it in  s}} ?: -1


    pub fn get_common(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
      let (mut i, mut j) = (0, 0);
      while i < nums1.len() && j < nums2.len() {
        if nums1[i] == nums2[j] { return nums1[i] }
        else if nums1[i] < nums2[j] { i += 1 } else { j += 1 }
      }; -1
    }