Count Numbers with Unique Digits - Complete Solution Guide
Count Numbers with Unique Digits is LeetCode problem 357, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given an integer n , return the count of all numbers with unique digits, x , where 0 <= x < 10 n . Example 1: Input: n = 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 Example 2: Input: n = 0 Output: 1 Constraints: 0 <= n <= 8
Detailed Explanation
The problem asks us to count the number of integers with unique digits within the range [0, 10<sup>n</sup>). For instance, if n=2, we need to count the numbers from 0 to 99, excluding numbers like 11, 22, 33, ..., 99 which have repeating digits. If n=0, we only have the number 0, so the count is 1.
Solution Approach
The solution uses a dynamic programming approach (although implemented iteratively) to calculate the number of integers with unique digits for each length from 1 to `n`. It builds upon the counts from smaller lengths to derive the count for larger lengths. It avoids generating each number and explicitly checking if digits are unique, instead leveraging mathematical principles to compute the result directly.
Step-by-Step Algorithm
- Step 1: Handle the base case: if n is 0, return 1 (only the number 0 is considered).
- Step 2: Initialize `total` to 10. This accounts for the numbers 0-9 when n >= 1.
- Step 3: Initialize `unique_count` to 9, which represents the number of unique one-digit numbers (1-9).
- Step 4: Initialize `available_digits` to 9, representing the digits available for the second position onward.
- Step 5: Iterate from i = 2 to n (inclusive). In each iteration, update `unique_count` by multiplying it with `available_digits`. This computes the count of unique digit numbers of length `i`. Then add `unique_count` to the `total`. Reduce available_digits by 1 for the next iteration, as we have one less unique digit to choose from.
- Step 6: Return the `total`, which is the sum of all unique digit numbers from length 0 to n.
Key Insights
- Insight 1: The number of unique digits available decreases as the length of the number increases. We start with 9 available digits (1-9) for the first digit (since it can't be 0), then 9 for the second digit (0-9 except the first digit), then 8, and so on.
- Insight 2: The problem can be solved iteratively or recursively. The number of unique digit numbers of length `i` depends on the number of unique digit numbers of length `i-1`.
- Insight 3: The constraint n <= 8 is important because if n > 10, there cannot be a number with unique digits (since we only have 10 digits from 0-9).
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Math, Dynamic Programming, Backtracking.
Companies
Asked at: J.P. Morgan.