Skip to content

3032. Count Numbers With Unique Digits II 👍

  • Time: $O(b - a)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int numberCount(int a, int b) {
    int ans = 0;
    for (int num = a; num <= b; ++num)
      if (isUniqueDigits(num))
        ++ans;
    return ans;
  }

 private:
  bool isUniqueDigits(int num) {
    vector<bool> seen(10);
    while (num > 0) {
      const int digit = num % 10;
      if (seen[digit])
        return false;
      seen[digit] = true;
      num /= 10;
    }
    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int numberCount(int a, int b) {
    int ans = 0;
    for (int num = a; num <= b; ++num)
      if (isUniqueDigits(num))
        ++ans;
    return ans;
  }

  private boolean isUniqueDigits(int num) {
    boolean[] seen = new boolean[10];
    while (num > 0) {
      final int digit = num % 10;
      if (seen[digit])
        return false;
      seen[digit] = true;
      num /= 10;
    }
    return true;
  }
}
1
2
3
4
class Solution:
  def numberCount(self, a: int, b: int) -> int:
    return sum(len(set(str(num))) == len(str(num))
               for num in range(a, b + 1))