Numbers With Repeated Digits
Hard
Topics
Given an integer n, return the count of positive integers in the range [1, n] that have at least one repeated digit.
Example 1
Input: n = 20 Output: 1 Explanation: Only 11 has a repeated digit.
Example 2
Input: n = 100 Output: 10
Example 3
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
- Add
9 × P(9, len-1)for every length belown's digit count. - Walk
n's digits, addingP(9-i, L-i-1)for each smaller unused digit placeable at positioni. - Break if
n's digit at this position repeats an earlier one. - If the walk finished, add one for
nitself. - Return
nminus 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 100Complexity
- Time — O(d²) where
dis the digit count, at most 10 here: the outer walk isdpositions and each tries at most 10 candidate digits with an O(d) permutation product. Measured at 5 microseconds forn = 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. Aftericommitted positions,idigits are spoken for, leaving10-ivalues — but one of the choices at this position is also consumed, so the suffix draws from9-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
nitself when its digits are distinct. The walk counts numbers strictly belown. - 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 - distinctimport java.util.*;
class Solution {
public int numDupDigitsAtMostN(int n) {
char[] s = Integer.toString(n).toCharArray();
int L = s.length;
// Count numbers in [1, n] with all-distinct digits, then subtract.
long distinct = 0;
for (int len = 1; len < L; len++) distinct += 9L * perm(9, len - 1);
boolean[] used = new boolean[10];
boolean prefixIsDistinct = true;
for (int i = 0; i < L; i++) {
int d = s[i] - '0';
int low = (i == 0) ? 1 : 0;
for (int cand = low; cand < d; cand++) {
if (used[cand]) continue;
distinct += perm(9 - i, L - i - 1);
}
if (used[d]) { prefixIsDistinct = false; break; }
used[d] = true;
}
if (prefixIsDistinct) distinct += 1;
return (int) (n - distinct);
}
private long perm(int m, int k) {
long r = 1;
for (int i = 0; i < k; i++) r *= (m - i);
return r;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
long long perm(int m, int k) {
long long r = 1;
for (int i = 0; i < k; i++) r *= (m - i);
return r;
}
public: int numDupDigitsAtMostN(int n) {
string s = to_string(n);
int L = s.size();
// Count numbers in [1, n] with all-distinct digits, then subtract.
long long distinct = 0;
for (int len = 1; len < L; len++) distinct += 9LL * perm(9, len - 1);
vector<bool> used(10, false);
bool prefixIsDistinct = true;
for (int i = 0; i < L; i++) {
int d = s[i] - '0';
int low = (i == 0) ? 1 : 0;
for (int cand = low; cand < d; cand++) {
if (used[cand]) continue;
distinct += perm(9 - i, L - i - 1);
}
if (used[d]) { prefixIsDistinct = false; break; }
used[d] = true;
}
if (prefixIsDistinct) distinct += 1;
return (int)(n - distinct);
}
};/**
* @param {number} n
* @return {number}
*/ var numDupDigitsAtMostN = function(n) {
const s = String(n);
const L = s.length;
const perm = (m, k) => {
let r = 1;
for (let i = 0; i < k; i++) r *= (m - i);
return r;
};
// Count numbers in [1, n] with all-distinct digits, then subtract.
let distinct = 0;
for (let len = 1; len < L; len++) distinct += 9 * perm(9, len - 1);
const used = new Array(10).fill(false);
let prefixIsDistinct = true;
for (let i = 0; i < L; i++) {
const d = s.charCodeAt(i) - 48;
const low = (i === 0) ? 1 : 0;
for (let cand = low; cand < d; cand++) {
if (used[cand]) continue;
distinct += perm(9 - i, L - i - 1);
}
if (used[d]) { prefixIsDistinct = false; break; }
used[d] = true;
}
if (prefixIsDistinct) distinct += 1;
return n - distinct;
};