Form Smallest Number From Two Digit Arrays Problem
#2605
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2605.
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 <= 91 <= nums1[i], nums2[i] <= 9- All digits in each array are unique.
Solution
Approach: Enumeration
If the two arrays share a digit, the smallest shared digit is a candidate on its own. Otherwise a number must use one digit a from nums1 and one digit b from nums2, and the smaller of ab and ba is the candidate. Try every pair and keep the smallest candidate. (A one-digit shared number is always smaller than any two-digit number, so the minimum handles both cases.)
Complexity: time O(mn), space O(1), where m and n are the lengths of the arrays.
class Solution:
def minNumber(self, nums1: List[int], nums2: List[int]) -> int:
ans = 100
for a in nums1:
for b in nums2:
if a == b:
ans = min(ans, a)
else:
ans = min(ans, 10 * a + b, 10 * b + a)
return ans