Count Numbers with Unique Digits

Description

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n10^n.

Example:

Input: 2
Output: 91 
Explanation: The answer should be the total numbers in the range
             of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99

Solutions

Let f(i)f(i) be the number of ii-digit numbers with unique digits.

f(0)=1.f(1)=10.f(i)=998...(11i),2i10.f(0) = 1. f(1) = 10. f(i) = 9 \cdot 9 \cdot 8 \cdot ... \cdot (11 - i), 2 \le i \le 10.

The the total number of numbers in the range of [0,10n)[0, 10^n) with unique digits are 0imin(n,10)f(i)\sum_{0 \le i \le min(n, 10)} f(i).

My solution

class Solution {
public:
    int uniqueDigits(int i){
        int count = 9;
        for(int j = 9; j > 0 && i > 0; --j, --i){
            count *= j;
        }
        return count;
    }
    
    int countNumbersWithUniqueDigits(int n) {
        if(n == 0) return 1;
        int count = 10;
        for(int i = 1; i < min(n, 10); ++i){
            count += uniqueDigits(i);
        }
        return count;
    }
};

More efficient implementation

class Solution {
public:
    int uniqueDigits(int i){
        int count = 9;
        for(int j = 9; j > 0 && i > 0; --j, --i){
            count *= j;
        }
        return count;
    }
    
    int countNumbersWithUniqueDigits(int n) {
        if(n == 0) return 1;
        int count = 10;
        int prod = 9;
        for(int i = 1; i < min(n, 10); ++i){
            prod *= (10 - i);
            count += prod;
        }
        return count;
    }
};

Last updated