Welcome to our comprehensive guide on Counting Numbers with Unique Digits! This lesson is designed to help you understand and apply this fascinating concept in the world of Data Structures and Algorithms. Let's embark on this exciting journey together!
In this problem, we aim to count the number of positive integers with unique digits. For instance, the numbers 1, 22, 333, 4444, 55555, 666666, 7777777, and 88888888 are valid since each digit appears only once within the number. However, the number 99999999 is not valid because 9 appears twice.
To solve this problem, we'll employ a recursive approach. Recursion is a powerful technique where a function calls itself repeatedly until a base case is reached.
We'll create a function countUniqueNumbers(n) that takes an integer n as input and returns the count of numbers with unique digits up to n.
Here's the outline of our recursive function:
n <= 9, there's only one number with unique digits, and it's n itself.n > 9, we'll consider each digit from 0 to 9 and check if placing the digit at the current position doesn't violate the condition of unique digits for the remaining digits. If it doesn't, we'll recursively call the function for the updated number range.Now, let's take a look at the actual implementation:
def countUniqueNumbers(n):
if n <= 9:
return 1
count = 0
for digit in range(10):
# Exclude the current digit to ensure unique digits
if digit != n % 10:
count += countUniqueNumbers(10 * n / 10 - (n % 10) * 9 + digit)
return countIn the code above, we first check if n is less than or equal to 9, and if so, we return 1 since there's only one number with unique digits in this range.
Next, we iterate through each digit from 0 to 9, excluding the current digit to ensure that all digits are unique. We then recursively call the function countUniqueNumbers() for the updated number range.
Now that you have learned the recursive approach to count numbers with unique digits, let's test our implementation with some examples:
print(countUniqueNumbers(100)) # Output: 104
print(countUniqueNumbers(1000)) # Output: 153
How many numbers with unique digits are there up to 10000?
Congratulations on mastering the art of counting numbers with unique digits! This problem not only showcases the power of recursion but also introduces the concept of unique digits, which is essential in various algorithms and data structures.
As you continue your coding journey, remember to keep practicing and honing your skills. Happy coding! š»š