Skip to main content
Back to problems
#3032
Easy Algorithms

Count numbers with unique digits ii

Hash Table Math Dynamic Programming
87.0% acceptance
Mar 31, 2026
36
4
Given two positive integers a and b, return the count of numbers having unique digits in the range [a, b] (inclusive).

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn number_count(a: i32, b: i32) -> i32 {
    // Since b <= 1000, just iterate and check each number
    (a..=b).filter(|&x| {
      let mut seen = 0u16;
      let mut n = x;
      let mut unique = true;
      while n > 0 {
        let d = (n % 10) as u16;
        if seen & (1 << d) != 0 {
          unique = false;
          break;
        }
        seen |= 1 << d;
        n /= 10;
      }
      unique
    }).count() as i32
  }
}