2605. Form Smallest Number From Two Digit Arrays LeetCode Solution

In this guide, you will get 2605. Form Smallest Number From Two Digit Arrays LeetCode Solution with the best time and space complexity. The solution to Form Smallest Number From Two Digit Arrays problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Form Smallest Number From Two Digit Arrays solution in C++
  4. Form Smallest Number From Two Digit Arrays solution in Java
  5. Form Smallest Number From Two Digit Arrays solution in Python
  6. Additional Resources
2605. Form Smallest Number From Two Digit Arrays LeetCode Solution image

Problem Statement of Form Smallest Number From Two Digit Arrays

Given two arrays of unique digits nums1 and nums2, return the smallest number that contains at least one digit from each array.

Example 1:

Input: nums1 = [4,1,3], nums2 = [5,7]
Output: 15
Explanation: The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have.

Example 2:

Input: nums1 = [3,5,2,6], nums2 = [3,1,7]
Output: 3
Explanation: The number 3 contains the digit 3 which exists in both arrays.

Constraints:

1 <= nums1.length, nums2.length <= 9
1 <= nums1[i], nums2[i] <= 9
All digits in each array are unique.

Complexity Analysis

  • Time Complexity: O(81) = O(1)
  • Space Complexity: O(1)

2605. Form Smallest Number From Two Digit Arrays LeetCode Solution in C++

class Solution {
 public:
  int minNumber(vector<int>& nums1, vector<int>& nums2) {
    int ans = 89;  // the largest num we can have
    for (const int a : nums1)
      for (const int b : nums2)
        ans = min(ans, a == b ? a : min(a, b) * 10 + max(a, b));
    return ans;
  }
};
/* code provided by PROGIEZ */

2605. Form Smallest Number From Two Digit Arrays LeetCode Solution in Java

class Solution {
  public int minNumber(int[] nums1, int[] nums2) {
    int ans = 89; // the largest num we can have
    for (final int a : nums1)
      for (final int b : nums2)
        ans = Math.min(ans, a == b ? a : Math.min(a, b) * 10 + Math.max(a, b));
    return ans;
  }
}
// code provided by PROGIEZ

2605. Form Smallest Number From Two Digit Arrays LeetCode Solution in Python

class Solution:
  def minNumber(self, nums1: list[int], nums2: list[int]) -> int:
    return min(a if a == b else min(a, b) * 10 + max(a, b)
               for a in nums1
               for b in nums2)
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.