2605. Form Smallest Number From Two Digit Arrays

2605. Form Smallest Number From Two Digit Arrays

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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.

Difficulty : Easy

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int minNumber(int[] nums1, int[] nums2) {
TreeSet<Integer> s1 = toSet(nums1);
TreeSet<Integer> s2 = toSet(nums2);
int a = s1.first();
int b = s2.first();
s1.retainAll(s2);
if (!s1.isEmpty()) {
//have to create new TreeSet, otherwise will get exception
return new TreeSet<>(s1).first();
}
return Math.min(a, b) * 10 + Math.max(a, b);

}

public static TreeSet<Integer> toSet(int[] nums) {
return Arrays.stream(nums).boxed().collect(Collectors.toCollection(TreeSet::new));
}
}