Show problems as
Classic problem #3646HardBacktrackingBit Manipulation

Next Special Palindrome Number

Real-world version: The Next Number Where Every Digit Counts Itself
Tracked in this browser only
Read Next Special Palindrome Number on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

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