Form Smallest Number From Two Digit Arrays - Problem

Given two arrays of unique digits nums1 and nums2, return the smallest number that contains at least one digit from each array.

The result can be formed by concatenating digits from both arrays in any order. You want to minimize the overall numerical value of the result.

Example: If nums1 = [4,1,3] and nums2 = [5,7], possible numbers include 14, 15, 17, 34, 35, 37, 41, 43, 45, 47, 51, 53, 54, 57, 71, 73, 74, 75. The smallest is 14.

Input & Output

Example 1 — No Common Digits
$ Input: nums1 = [4,1,3], nums2 = [5,7]
Output: 15
💡 Note: No digits appear in both arrays. The smallest from nums1 is 1, from nums2 is 5. Between 15 and 51, we choose 15.
Example 2 — Common Digit Exists
$ Input: nums1 = [3,5,2,6], nums2 = [3,1,7]
Output: 3
💡 Note: Digit 3 appears in both arrays. Since we can form a single-digit number, 3 is smaller than any 2-digit combination.
Example 3 — Multiple Common Digits
$ Input: nums1 = [6,8,4,2], nums2 = [4,9,2,3]
Output: 2
💡 Note: Both 4 and 2 appear in both arrays. We choose the smaller common digit: 2.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 9
  • 1 ≤ nums1[i], nums2[i] ≤ 9
  • All digits in each array are unique

Visualization

Tap to expand
Form Smallest Number From Two Digit Arrays INPUT nums1 = [4, 1, 3] 4 1 3 nums2 = [5, 7] 5 7 Goal: Find smallest number with digit from each array min(nums1) = 1, min(nums2) = 5 ALGORITHM STEPS 1 Check Common Digits Find intersection of arrays common = [] (empty) 2 Find Minimum Each min1 = 1, min2 = 5 3 No Common Digit Combine minimums Decision Logic: if min1 < min2: result = min1 * 10 + min2 4 Calculate Result 1 * 10 + 5 = 15 result = 15 FINAL RESULT Smallest Valid Number: 15 Breakdown: 1 from nums1 5 from nums2 concat Verification: Contains 1 from nums1 - OK Contains 5 from nums2 - OK 15 is the smallest! Key Insight: If arrays share a common digit, return the smallest common digit (single digit is always smaller). Otherwise, combine the minimum digits from each array with the smaller one in tens place for smallest value. TutorialsPoint - Form Smallest Number From Two Digit Arrays | Optimal Greedy Solution
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
9.0K Views
Medium Frequency
~8 min Avg. Time
324 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen