Count Numbers with Unique Digits šŸŽÆ

beginner
24 min

Count Numbers with Unique Digits šŸŽÆ

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!

Understanding the Problem šŸ“

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.

Breaking Down the Solution šŸ’”

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.

The Recursive Function

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:

  1. Base case: If n <= 9, there's only one number with unique digits, and it's n itself.
  2. Inductive case: For 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:

python
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 count

In 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.

Putting It All Together āœ…

Now that you have learned the recursive approach to count numbers with unique digits, let's test our implementation with some examples:

  1. Example 1: Count the number of unique numbers up to 100.
print(countUniqueNumbers(100)) # Output: 104
  1. Example 2: Count the number of unique numbers up to 1000.
print(countUniqueNumbers(1000)) # Output: 153

Quiz Time šŸ’”

Quick Quiz
Question 1 of 1

How many numbers with unique digits are there up to 10000?

Wrapping Up šŸŽÆ

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! šŸ’»šŸŒŸ