Leetcode 2605. Form Smallest Number From Two Digit Arrays
LeetCode Problem 2605: Form Smallest Number From Two Digit Arrays
You are given two arrays of digits nums1 and nums2. You need to form the smallest possible number by picking one digit from nums1 and one digit from nums2.
nums1 is a and the smallest of nums2 is b, the numbers to consider are 10 * a + b and 10 * b + a. Return the smaller of these two numbers.#include <algorithm>
#include <unordered_set>
#include <vector>
#include <iostream>
class Solution {
public:
int minNumber(std::vector<int>& nums1, std::vector<int>& nums2) {
// Sort both arrays to find the smallest elements quickly
std::sort(nums1.begin(), nums1.end());
std::sort(nums2.begin(), nums2.end());
// Step 1: Check if there's a common digit
std::unordered_set<int> numSet(nums1.begin(), nums1.end());
for (int num : nums2) {
if (numSet.find(num) != numSet.end()) {
// Smallest common element forms the smallest number
return num;
}
}
// Step 2: No common digits, combine the smallest elements
int smallestNum1 = nums1.front(); // Smallest element in nums1
int smallestNum2 = nums2.front(); // Smallest element in nums2
// Create two possible numbers and return the smallest one
int num1 = smallestNum1 * 10 + smallestNum2;
int num2 = smallestNum2 * 10 + smallestNum1;
return std::min(num1, num2);
}
};
int main() {
Solution solution;
std::vector<int> nums1 = {4, 1, 3};
std::vector<int> nums2 = {5, 7, 3};
std::cout << solution.minNumber(nums1, nums2) << std::endl; // Output: 3
std::vector<int> nums1_case2 = {4, 1, 3};
std::vector<int> nums2_case2 = {5, 7, 2};
std::cout << solution.minNumber(nums1_case2, nums2_case2) << std::endl; // Output: 12
return 0;
}
nums1 takes (O(n \log n)), where (n) is the length of nums1.nums2 takes (O(m \log m)), where (m) is the length of nums2.nums1 into a set takes (O(n)).nums2 takes (O(m)).Combining these, the overall time complexity is (O(n \log n + m \log m)).
nums1.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?