Tally Repeat-Free Three-Digit Numbers Up To a Limit
Math & Bit ManipulationAuto-graded · 25 test casesLast updated
Count integers from 100 up to a given limit whose three digits are all different, using direct enumeration or combinatorial reasoning.
You are given an integer limit. Consider every integer from 100 up to and including limit. Each of these has exactly three decimal digits.
Call a number repeat-free if its three digits are pairwise different. For instance, 340 and 987 are repeat-free, while selected values such as felt 121, 366, and 100 are not, because some digit appears more than once.
Return how many integers in the range [100, limit] are repeat-free.
Details
- Both endpoints of the range are included, so
limititself is counted if it is repeat-free. - A digit
0is allowed in the tens or units position, as long as it does not appear twice. For example,102and130are repeat-free, but100and200are not. - The result is a single integer.
Constraints
100 <= limit <= 999limitis an integer.
Examples
Example 1
Input: count_repeat_free(105)
Output: 4
Example 2
Input: count_repeat_free(120)
Output: 9
Hints
Hint 1
There are at most 900 numbers in the range, so checking each one individually is perfectly fast.
Hint 2
A three-digit number has pairwise different digits exactly when the set of its digits contains 3 elements.
Hint 3
As a sanity check, for limit = 999 the answer must be 9 * 9 * 8 = 648 (first digit 1-9, second any other digit, third any remaining digit).
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The range holds at most 900 integers (100 through 999), so enumeration is the simplest correct method. Loop over every number from 100 to limit inclusive. Convert it to a string and build a set of its characters. The number is repeat-free exactly when that set has size 3. Add one to the counter for each such number.
Why it is correct
- The loop visits every integer in
[100, limit], includinglimit, so none is skipped. - Every number in the range has exactly three digits, so there are no leading-zero concerns.
- For a three-character string, the set size equals 3 only if all characters differ. If any two match, the set has size 2 or less.
- Each qualifying number adds exactly one to the count, so the final value is the size of the qualifying set.
Sanity checks: limit = 105 gives 102, 103, 104, 105, so 4. limit = 120 gives 102 through 109 (8 numbers) plus 120, so 9. limit = 999 gives 9 * 9 * 8 = 648.
Complexity
- Time: O(limit - 99), at most 900 iterations with constant work each, so effectively constant.
- Space: O(1).
Reference solution
def count_repeat_free(limit: int) -> int:
count = 0
for number in range(100, limit + 1):
digits = str(number)
if len(set(digits)) == 3:
count += 1
return count