Form Smallest Number From Two Digit Arrays - Complete Solution Guide
Form Smallest Number From Two Digit Arrays is LeetCode problem 2605, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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
Detailed Explanation
The problem asks to find the smallest number that can be formed using at least one digit from each of two input arrays, `nums1` and `nums2`. Both input arrays contain unique digits from 1 to 9. The output should be an integer representing this smallest number. If a digit exists in both arrays, that digit alone is the smallest number. Otherwise, the smallest number is formed by concatenating the smallest digits from each array.
Solution Approach
The Python and C++ solutions leverage sets to efficiently find the intersection of the two input arrays. If an intersection exists (a common digit), the minimum value from the intersection is returned. Otherwise, the minimum values from each array are found, and the smallest number formed by concatenating them (smallest digit first) is returned. The Java solution achieves the same but iterates through the arrays instead of using the set's min function.
Step-by-Step Algorithm
- Create sets `s1` and `s2` from `nums1` and `nums2` respectively. This allows for efficient checking of digit existence.
- Find the intersection of `s1` and `s2`. If the intersection is not empty, return the minimum value from the intersection.
- If the intersection is empty, find the minimum values `min1` from `nums1` and `min2` from `nums2`.
- Construct the smallest number by concatenating `min1` and `min2` (the smaller one first). Return this number.
Key Insights
- Using sets to efficiently check for intersections and find minimum values. Sets provide O(1) lookup time for checking the existence of a digit.
- Prioritizing finding a common digit between the two arrays. If a common digit is found, that is the solution.
- Handling the case where there's no common digit, requiring concatenation of the smallest digits from each array to form the smallest possible number.
Complexity Analysis
Time Complexity: O(n + m)
Space Complexity: O(n + m)
Topics
This problem involves: Array, Hash Table, Enumeration.
Companies
Asked at: Tinkoff.