#2605

Form Smallest Number From Two Digit Arrays

Easy
ArrayHash TableEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of generating all combinations, we can find the minimum digit in both arrays and check if they are the same. If they are, we return that digit. If not, we can combine the smallest digits from each array to form the smallest two-digit number.

⚙️

Algorithm

3 steps
  1. 1Step 1: Find the minimum digit in nums1 and nums2.
  2. 2Step 2: If the minimum digits are the same, return that digit.
  3. 3Step 3: If they are different, return the combination of the two smallest digits in ascending order.
solution.py7 lines
1def smallestNumber(nums1, nums2):
2    min1 = min(nums1)
3    min2 = min(nums2)
4    if min1 == min2:
5        return min1
6    return min(min1 * 10 + min2, min2 * 10 + min1)
7

Complexity note: This solution is linear because we only need to find the minimum values from both arrays, which can be done in a single pass each.

  • 1The smallest number can be formed by either a single digit or a combination of two digits.
  • 2Finding the minimum digits in both arrays is crucial for optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.