All problems
1069HardBacktrackingBit Manipulation

The Next Number Where Every Digit Counts Itself

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3646Next Special Palindrome Number

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A whole number is self-counting when it reads the same backwards as forwards and, for every digit it uses, that digit appears exactly as many times as the digit itself. So a 4 may only appear in a number holding exactly four of them, and a 0 can never appear at all, since it would have to appear no times.

Return the smallest self-counting number strictly above n.

Examples

Example 1

Input
n = 0
Output
1

A single `1` is self-counting, since it reads the same both ways and the digit one appears once.

Example 2

Input
n = 1
Output
22

Nothing between two and twenty-one works, since any such number either fails to read the same backwards or holds a digit the wrong number of times. Two twos do both.

Example 3

Input
n = 45
Output
212

No two-digit number above forty-five is self-counting, so the answer has three digits: one `1` in the middle with a `2` on either side.

Constraints

  • 0 <= n <= 10^15

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def special_palindrome(n: int) -> int:
Java
public long specialPalindrome(long n)
September 7
Apply