Leetcode 2605. Form Smallest Number From Two Digit Arrays
You have two arrays of digits, nums1
and nums2
. Return the smallest number that contains at least one digit from each of the arrays.
nums1
and nums2
will each contain at least one digit.To solve this problem, we need to consider the following steps:
nums1
and the smallest digit in nums2
and combine them in both possible orders (e.g., for digits a
and b
, consider ab
and ba
), then return the smaller of the two combinations.Here’s how you can implement the solution in Java:
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int formSmallestNumber(int[] nums1, int[] nums2) {
boolean[] digits1 = new boolean[10];
boolean[] digits2 = new boolean[10];
// Mark the digits present in nums1
for (int num : nums1) {
digits1[num] = true;
}
// Mark the digits present in nums2
for (int num : nums2) {
digits2[num] = true;
}
// Find the smallest common digit if present
for (int i = 0; i < 10; i++) {
if (digits1[i] && digits2[i]) {
return i;
}
}
// Find the smallest digit in nums1
int min1 = Integer.MAX_VALUE;
for (int num : nums1) {
if (num < min1) {
min1 = num;
}
}
// Find the smallest digit in nums2
int min2 = Integer.MAX_VALUE;
for (int num : nums2) {
if (num < min2) {
min2 = num;
}
}
// Combine the digits to form the smallest number
int combined1 = min1 * 10 + min2;
int combined2 = min2 * 10 + min1;
// Return the smallest combination
return Math.min(combined1, combined2);
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums1 = {4, 1, 3};
int[] nums2 = {5, 7};
System.out.println(solution.formSmallestNumber(nums1, nums2)); // Output: 15
}
}
n
is the length of nums1
and m
is the length of nums2
. This is because we are making a single pass through each array to mark the presence of digits and to find the minimum digits.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?