Leetcode 357. Count Numbers with Unique Digits
Given a non-negative integer n, return the count of all numbers with unique digits, x, where 0 ≤ x < 10^n.
n be 0?
n can be 0.n?
n is a non-negative integer, typically n <= 10 because 10^n will have more digits than can fit in a standard integer.n is 0?
n is 0, the count of numbers with unique digits is 1 (0 itself).To solve this problem, we can use a mathematical approach rather than generating each number and checking its uniqueness. Let’s break down the idea:
n is greater than 10, we can’t have more than 10 unique digits because there are only 10 digits (0-9).i from 1 to n, we calculate the number of unique numbers of length i.Steps:
n is 0, return 1.2 to n:
2, there are 9 * 9 possible numbers (because the first digit can’t be 0).3, there are 9 * 9 * 8 possible numbers (because the first digit can’t be 0 and the second digit can be any of the 9 remaining digits, the third digit can be any of the 8 remaining digits).Repeat this pattern up to n.
public class Solution {
public int countNumbersWithUniqueDigits(int n) {
if (n == 0) return 1;
int uniqueDigitsCount = 10; // For n = 1, there are 10 unique digits (0-9)
int availableDigits = 9;
int currentCount = 9;
for (int i = 2; i <= n && availableDigits > 0; i++) {
currentCount *= availableDigits;
uniqueDigitsCount += currentCount;
availableDigits--;
}
return uniqueDigitsCount;
}
}
The time complexity of the solution is O(n), where n is the input number. This is because the maximum number of iterations the loop will run is n.
The space complexity is O(1) because we are using a constant amount of extra space to store the counts and the factorial-like computations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?