We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Form Smallest Number From Two Digit Arrays

Number: 2668

Difficulty: Easy

Paid? No

Companies: Tinkoff


Problem Description

Given two arrays of unique digits nums1 and nums2, return the smallest number that contains at least one digit from each array. If a digit exists in both arrays, it alone qualifies as the smallest possible number.


Key Insights

  • Check for a common digit between the two arrays.
  • If a common digit exists, the smallest common digit is the answer.
  • If no common digit is found, construct the smallest possible two-digit number using the smallest digit from each array.
  • With each array containing at most 9 unique digits, iterating over possible digits is efficient.

Space and Time Complexity

Time Complexity: O(1) (operations are bounded by a constant, as the maximum digits are 9 in each array) Space Complexity: O(1) (only a few additional variables are used)


Solution

First, convert both arrays to sets and check for any common digits. If a common digit exists, return the smallest one from the intersection. Otherwise, find the smallest digit from each array, and combine them in increasing order (i.e., if min1 < min2, combine as min1 followed by min2; otherwise, use the reverse) to form the smallest two-digit number. This approach leverages simple set operations and comparison logic.


Code Solutions

# Python solution with line-by-line comments
def minNumber(nums1, nums2):
    # Convert nums1 and nums2 to sets to find the intersection easily
    set1 = set(nums1)
    set2 = set(nums2)
    
    # Find common digits between the two sets
    common_digits = set1 & set2
    # If any common digit exists, return the smallest one
    if common_digits:
        return min(common_digits)
    
    # Find the smallest digits in both arrays
    min1 = min(nums1)
    min2 = min(nums2)
    
    # Form the two-digit number by arranging the two smallest digits in increasing order
    if min1 < min2:
        return int(str(min1) + str(min2))
    else:
        return int(str(min2) + str(min1))

# Testing the function
print(minNumber([4, 1, 3], [5, 7]))  # Expected output: 15
print(minNumber([3, 5, 2, 6], [3, 1, 7]))  # Expected output: 3
← Back to All Questions