HardNo. 1012

Numbers With Repeated Digits — LeetCode 1012 Python Solution

Topics
Math, Dynamic Programming
Reading time
3 min

The problem

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

Example

Input
n = 20
Output
1
Explanation
The only positive number (<= 20) with at least 1 repeated digit is 11.

Python solution

PythonSolution
class Solution:
    def numDupDigitsAtMostN(self, n: int) -> int:
        @cache
        def dfs(i: int, mask: int, lead: bool, limit: bool) -> int:
            if i >= len(s):
                return lead ^ 1
            up = int(s[i]) if limit else 9
            ans = 0
            for j in range(up + 1):
                if lead and j == 0:
                    ans += dfs(i + 1, mask, True, False)
                elif mask >> j & 1 ^ 1:
                    ans += dfs(i + 1, mask | 1 << j, False, limit and j == up)
            return ans

        s = str(n)
        return n - dfs(0, 0, True, True)

Complexity

Time
O(log n × 2D × D)
Space · auxiliary
O(log n × 2D)

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1012. Numbers With Repeated Digits is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0062Unique PathsMedium
0070Climbing StairsEasy
0096Unique Binary Search TreesMedium
0233Number of Digit OneHard
0241Different Ways to Add ParenthesesMedium
0279Perfect SquaresMedium

Frequently asked questions

How hard is LeetCode 1012. Numbers With Repeated Digits?

LeetCode 1012. Numbers With Repeated Digits is rated Hard on LeetCode.

What is the time complexity of LeetCode 1012. Numbers With Repeated Digits?

The Python solution on this page runs in O(log n × 2D × D).

What is the space complexity of LeetCode 1012. Numbers With Repeated Digits?

The Python solution on this page uses O(log n × 2D) auxiliary space.

What topics does LeetCode 1012. Numbers With Repeated Digits cover?

LeetCode 1012. Numbers With Repeated Digits is tagged Math and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.