Problem 1012

Abstract / Summary

Count numbers with at least one repeated digit up to a given limit.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1012.py

class Solution:
    def numDupDigitsAtMostN(self, n: int) -> int:
        # "repeated digits" doesn't mean they have to be next to each other
        # I found it out the hard way ...
        result = 0

        # split into list of digits
        n    = [ int(c) for c in str(n) ]
        size = len(n)

        @cache
        def deeper(need, used, zero, repeated, limit): # used is a bitmask
            if need == 0:
                return 1 if repeated else 0 # 1 if True

            last  = n[-need]
            count = 0
            for digit in range(10):
                # respect upper limit
                if limit and digit > last:
                    break

                # no more leading zeros
                if digit == 1:
                    zero = False

                mask = 1 << digit
                next = used | mask

                if zero:
                    next = 0 # don't count leading zeros

                same = repeated or (used & mask)
                if same:
                    next = 0 # reduce number of memoized states

                count += deeper(need - 1, next, zero, same, limit and digit == last)

            return count

        return deeper(size, 0, True, False, True)
41 lines | 1273 bytes | submitted May 30, 2024 | GitHub   34% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 42% (40k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes how many integers in the range [0, N] contain at least one repeated digit. It treats “repeated” as any digit that appears more than once, regardless of adjacency. The algorithm works by constructing the decimal representation of N, then performing a depth-first search over all possible digit positions while respecting the upper bound and tracking which digits have already been used. Memoization via functools.cache eliminates redundant work, making the solution efficient even for the largest 32-bit inputs.

Digit Extraction

The first logical step converts the integer N into a list of its decimal digits. This list is used throughout the recursion to enforce the “tight” condition when the current prefix matches the prefix of N.

n    = [int(c) for c in str(n)]
size = len(n)

The list n holds the most-significant digit at index 0 and the least-significant digit at the last index. The variable size records the total number of digits, which determines the depth of the recursion.

Recursive Exploration

A nested function deeper performs the core enumeration. Its signature is

def deeper(need, used, zero, repeated, limit):
  • need - how many positions remain to be filled. When it reaches zero, a complete number has been formed.
  • used - a bitmask representing which digits have already appeared in the current prefix.
  • zero - a flag indicating whether the current position is still part of leading zeros.
  • repeated - a flag that becomes true once a digit is chosen that already exists in used.
  • limit - a flag that is true only when the prefix built so far is exactly equal to the prefix of N; it forces the next digit not to exceed the corresponding digit in n.

The recursion terminates when need == 0. At that point the function returns 1 if a repeated digit has been encountered, otherwise 0. This return value contributes to the total count of numbers with repeated digits.

if need == 0:
    return 1 if repeated else 0

Upper-Bound Enforcement

Inside the loop over possible digits, the code respects the tight bound by checking limit and comparing the candidate digit with the corresponding digit from n. If the candidate exceeds the allowed maximum, the loop breaks early, preventing any exploration of numbers that would surpass N.

if limit and digit > last:
    break

Handling Leading Zeros

The flag zero tracks whether the current position is still a leading zero. When zero is true, the algorithm treats the digit selection as not contributing to the used-digit set, effectively ignoring leading zeros in the uniqueness check. The transition out of the leading-zero state occurs when a non-zero digit is placed.

if digit == 1:
    zero = False

When zero remains true for a given digit, the next mask is reset to zero, ensuring that leading zeros do not pollute the used bitmask.

if zero:
    next = 0

Detecting Repeated Digits

The expression used & mask determines whether the current digit has already appeared. If it has, the repeated flag becomes true for the remainder of the recursion. Additionally, when a repetition is detected, the next mask is cleared to reduce the number of distinct memoization states, because the exact composition of used no longer matters once a repeat has occurred.

same = repeated or (used & mask)
if same:
    next = 0

Recursive Call Construction

Each iteration computes the next state and recurses with one fewer digit to fill. The limit flag for the child call is the logical AND of the current limit and the condition that the chosen digit equals the corresponding digit in n. This propagation maintains the tight constraint only as long as the prefix matches N.

count += deeper(
    need - 1,
    next,
    zero,
    same,
    limit and digit == last
)

The accumulated count is returned to the caller, representing the number of valid numbers in the sub-tree that contain a repeated digit.

Memoization

The decorator @cache applied to deeper automatically stores results for each unique combination of arguments. Because the state space is defined by a small set of parameters (need, used, zero, repeated, limit), many sub-problems are revisited during the depth-first traversal. Caching eliminates repeated computation, turning an exponential-looking search into a tractable dynamic programming solution.

Edge Cases Managed

The algorithm gracefully handles the case where N is a single-digit number. In that scenario size equals 1, and the recursion explores digits from 0 to the sole digit of N. Since a single digit cannot repeat, the base case returns 0, yielding the correct overall result of zero repeated-digit numbers.

When N contains zeros in its interior (e.g., 101), the leading-zero logic ensures that zeros occurring after the first non-zero digit are treated like any other digit. The bitmask correctly records a zero that appears after the leading region, allowing the detection of a repeated zero.

If N itself contains repeated digits, the tight-bound mechanism still permits the exact value of N to be counted, because the final call reaches need == 0 with repeated set to true. Thus the function includes N in the total when appropriate.

The handling of the digit 1 as the trigger to exit the leading-zero state (if digit == 1: zero = False) is a subtle detail that ensures the transition occurs on the first non-zero digit, regardless of whether that digit is 1 or any other non-zero value. The subsequent logic still works because the flag zero is already false for any later non-zero digit.

Performance Optimizations

The primary optimization is the use of a bitmask (used) to represent the set of digits already seen. Bitwise operations (<<, |, &) are constant-time and compact, allowing the algorithm to test membership and update the set efficiently.

Clearing the next mask when a repetition has been detected (if same: next = 0) reduces the dimensionality of the memoization table. After a repeat occurs, the exact composition of previously used digits no longer influences future decisions, so collapsing those states prevents an explosion of cached entries.

The early break in the digit loop (if limit and digit > last: break) prunes branches that would exceed the upper bound, avoiding unnecessary recursive calls for numbers that are guaranteed to be out of range.

Finally, the recursion proceeds from the most significant digit toward the least significant digit, aligning with the natural order of the decimal representation. This ordering simplifies the tight-bound logic and ensures that each recursive level works with a smaller need value, guaranteeing termination.

Final Result

The outer call initiates the recursion with the full length of the number, an empty used-digit mask, the leading-zero flag set to true, no repetition detected yet, and the limit flag active.

return deeper(size, 0, True, False, True)

The returned integer is the count of integers between 0 and the original N (inclusive) that contain at least one repeated digit, computed efficiently through memoized depth-first enumeration with bitmask state compression.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a huge box filled with all the numbers from one up to a secret target number. The goal is to find how many of those numbers have at least one digit that shows up more than once, like the number eleven where the one appears twice.

To solve this, the code acts like a very careful counter that looks at every single position in the number one step at a time. It uses a special trick called memoization which is like having a notepad to remember answers to questions already asked so there is no need to count the same things over and over again.

The code starts by turning the target number into a list of individual digits. Then it starts a chain reaction of logic that checks every digit place. It keeps track of whether it has already seen a digit before by using a tiny bit of data called a bitmask. Think of the bitmask as a hand with ten fingers where a finger stands up if the digit has been used. If the code picks a digit that has its finger already standing up, then it knows it has found a repeated number.

It keeps moving through the positions, making sure not to go past the target number. If it finds a number with a repeat, it adds that to a growing pile. By the time it finishes checking every possibility, it has the final answer.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.48 | σ = 2.20

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
lzl124631x C++
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lzl124631x C++
suxrobGM C#
wisdompeak C++
27 links | 14 authors | 7 languages

Videos

2 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

7 solutions   May 30, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality