Problem Description
Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.
Key Insights
- Instead of directly counting numbers with repeated digits, count the numbers with all unique digits and subtract from n.
- Use combinatorial methods to calculate the number of numbers with distinct digits for lengths smaller than the length of n.
- Count numbers with the same number of digits as n using digit-by-digit analysis while avoiding repetitions.
- The limited set of digits (0-9) allows the use of permutation formulas without incurring high computational costs.
Space and Time Complexity
Time Complexity: O(10) per operation as the maximum digit length is 10. Space Complexity: O(1)
Solution
The approach involves counting numbers with unique digits up to n and then subtracting that count from n to find numbers that have at least one repeated digit. First, count numbers with fewer digits than n using permutation formulas (9 * P(9, k-1) for each valid k). Then, for numbers having the same digit length as n, iterate through each digit and count the valid choices for that digit that have not already been used, using permutations for the remaining positions. The trick is careful handling of repetitions and the restriction on zero for the leading digit.