Numbers With Repeated Digits

Hard

Topics
MathDynamic Programming

Given an integer n, return the count of positive integers in the range [1, n] that have at least one repeated digit.

Example 1

1234567891011121314151617181920
has a repeated digit
Shaded numbers repeat a digit. Counting those directly is awkward, so the standard move is to count the numbers with all-distinct digits by digit-length and subtract from 20.
Cells are the integers up to n; shaded ones repeat a digit.
Input:  n = 20
Output: 1
Explanation: Only 11 has a repeated digit.

Example 2

123456789101112131415161718192021222324
has a repeated digit
The figure shows only the first 24.
Input:  n = 100
Output: 10

Example 3

123456789101112131415161718192021222324
has a repeated digit
Input:  n = 1000
Output: 262

Constraints

  • 1 <= n <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

Counting numbers that have a repeat is awkward because "has a repeat" is a property of the whole number. Counting the complement is easy, because "all digits distinct" is a sequence of independent per-position choices. So count the distinct-digit numbers in [1, n] and subtract from n.

Split that count by length. For lengths strictly below n's, every such number is unconstrained: nine choices for a nonzero leading digit, then an ordered selection from the nine remaining digit values — 9 × P(9, len-1).

For the exact length of n, walk its digits. At position i, placing any unused digit smaller than n's digit there guarantees the number stays below n, and the L-i-1 positions after it can be any distinct arrangement of the 9-i digits still free. Then commit to n's own digit and continue — unless it repeats one already used, in which case no longer prefix is valid and the walk stops. If the walk completes, n itself has distinct digits and counts for one more.

Approach

  1. Add 9 × P(9, len-1) for every length below n's digit count.
  2. Walk n's digits, adding P(9-i, L-i-1) for each smaller unused digit placeable at position i.
  3. Break if n's digit at this position repeats an earlier one.
  4. If the walk finished, add one for n itself.
  5. Return n minus the total.

Dry Run

n = 1000

shorter lengths
  len 1:  9 * P(9,0) = 9       the digits 1..9
  len 2:  9 * P(9,1) = 81
  len 3:  9 * P(9,2) = 648

same length (4 digits, "1000")
  position 0, digit 1: no smaller nonzero digit, nothing to add
  position 1, digit 0: nothing smaller than 0
  position 2, digit 0: 0 is already used by position 1 -> break

distinct-digit count = 9 + 81 + 648 = 738
answer = 1000 - 738 = 262

  n = 20  -> 1      only 11 repeats
  n = 100 -> 10     11, 22, ... 99, and 100

Complexity

  • Time — O(d²) where d is the digit count, at most 10 here: the outer walk is d positions and each tries at most 10 candidate digits with an O(d) permutation product. Measured at 5 microseconds for n = 10⁹.
  • Space — O(d) for the digit list and the used-digit set.
  • The direct scan — test every number from 1 to n — is O(n·d). It is the obvious first answer and it is worth stating, but at the stated bound of 10⁹ it needs roughly ten minutes, measured by extrapolating from 2×10⁶ in 1.19 seconds. The combinatorial count is not an optimisation here; it is the difference between answering and not.

Common Pitfalls

  • Writing the direct scan and calling it done. It is correct and it cannot finish at n = 10⁹.
  • Forgetting that the leading digit cannot be 0, which overcounts every shorter length.
  • Using P(10-i, ...) for the free suffix. After i committed positions, i digits are spoken for, leaving 10-i values — but one of the choices at this position is also consumed, so the suffix draws from 9-i.
  • Continuing the prefix walk after n's own digit repeats. Once the prefix is invalid, every longer prefix is too, and counting past the break double-counts.
  • Forgetting to add one for n itself when its digits are distinct. The walk counts numbers strictly below n.
  • Counting the number 0. The range starts at 1, which is why the shorter-length formula uses a nonzero leading digit and never produces 0.

Full Solution — all languages

class Solution:
    def numDupDigitsAtMostN(self, n):
        digits = [int(c) for c in str(n)]
        L = len(digits)

        def perm(m, k):
            """m * (m-1) * ... * (m-k+1): ordered choices of k from m."""
            r = 1
            for i in range(k):
                r *= m - i
            return r

        # Count the numbers in [1, n] whose digits are all distinct, then
        # subtract. Counting the complement is far easier: a repeat is a global
        # property, distinctness is a per-position choice.
        distinct = 0

        # Shorter than n: a nonzero leading digit, then any ordered selection
        # from the nine remaining digit values.
        for length in range(1, L):
            distinct += 9 * perm(9, length - 1)

        # Exactly as long as n: walk the prefix, and at each position count the
        # numbers that stay below n by placing a smaller unused digit here and
        # anything distinct afterwards.
        used = set()
        for i, d in enumerate(digits):
            low = 1 if i == 0 else 0
            for cand in range(low, d):
                if cand in used:
                    continue
                distinct += perm(9 - i, L - i - 1)
            if d in used:
                break          # n itself repeats, so the prefix walk stops here
            used.add(d)
        else:
            distinct += 1      # the loop finished, so n has distinct digits

        return n - distinct
SensAI
Beta
Tap the mic to stop voice mode