Skip to main content
Back to problems
#2605
Easy Algorithms

Form smallest number from two digit arrays

Array Hash Table Enumeration
55.0% acceptance
Feb 25, 2026
328
29
Given two arrays of unique digits nums1 and nums2, return the smallest number that contains at least one digit from each array.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_number(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
    use std::collections::HashSet;
    let set1: HashSet<i32> = nums1.iter().copied().collect();
    let set2: HashSet<i32> = nums2.iter().copied().collect();

    // Check common digits
    let mut common: Vec<i32> = set1.intersection(&set2).copied().collect();
    if !common.is_empty() {
      common.sort_unstable();
      return common[0];
    }

    let min1 = *nums1.iter().min().unwrap();
    let min2 = *nums2.iter().min().unwrap();

    // Smallest two-digit number: smaller digit first
    if min1 < min2 {
      min1 * 10 + min2
    } else {
      min2 * 10 + min1
    }
  }
}