Data Structures & AlgorithmsVery hardInfosys SP/DSE · Product Company SDE

Problem: Find how many numbers in 1..n have all distinct digits — the digit-DP-free shortcut for n = 10ᵏ uses counting.

Problem: Find how many numbers in 1..n have all distinct digits — the digit-DP-free shortcut for n = 10ᵏ uses counting.
def distinct_upto_pow10(k):
    total, avail, prod = 1, 9, 9      # 1 counts the number 0
    for d in range(1, k + 1):
        total += prod
        prod *= avail; avail -= 1
    return total
print(distinct_upto_pow10(2), distinct_upto_pow10(3), sum(len(set(str(x))) == len(str(x)) for x in range(1000)))
What is printed?
  1. A. 90 738 739
  2. B. 91 739 739
  3. C. 91 648 739
  4. D. 100 739 739

Correct answer: B. 91 739 739

Numbers with d digits and no repeats: 9 · 9 · 8 · … (first digit 1–9, then the remaining choices). Below 100: 1 (zero) + 9 + 81 = 91. Below 1000: add 9·9·8 = 648 → 739, confirmed by brute force over 0..999. O(k) versus O(10ᵏ).

More Coding Interview Problems questions

Exams that ask this topic