Next Special Palindrome Number Problem
Description
LeetCode Problem 3646.
You are given an integer n.
A number is called special if:
- It is a palindrome.
- Every digit
kin the number appears exactlyktimes.
Return the smallest special number strictly greater than n.
Example 1:
Input: n = 2
Output: 22
Explanation:
22 is the smallest special number greater than 2, as it is a palindrome and the digit 2 appears exactly 2 times.
Example 2:
Input: n = 33
Output: 212
Explanation:
212 is the smallest special number greater than 33, as it is a palindrome and the digits 1 and 2 appear exactly 1 and 2 times respectively.
Constraints:
0 <= n <= 10^15
Solution
Approach: Enumerate All Special Palindromes
A special number has digit d exactly d times, so its length is the sum of its distinct digits. Digit 0 cannot appear (it would have to appear zero times), and the digits come from 1..9. Since n <= 10^15, the answer has at most 17 digits, so only digit sets with sum at most 17 matter. There are just 511 non-empty subsets of {1..9}.
A palindrome pairs up its digits, so at most one digit may have an odd count, and that digit goes in the middle. For each valid subset:
- Take
d / 2copies of each digitdas the left half. - Generate every distinct arrangement of the half by depth-first search, picking one digit at a time.
- Mirror the half (around the odd digit, if there is one) to get the number.
Keep the smallest generated number that is strictly greater than n. The number of candidates is small (a few thousand per subset at most), so this is fast.
Complexity: a constant amount of work, since the candidate set does not depend on n.
class Solution:
def specialPalindrome(self, n: int) -> int:
best = 10**18
cnt = [0] * 10
def build(half, left, mid):
# place `left` more half-digits, then mirror the half around `mid`
nonlocal best
if left == 0:
v = int(half + mid + half[::-1])
if n < v < best:
best = v
return
for d in range(1, 10):
if cnt[d] > 0:
cnt[d] -= 1
build(half + str(d), left - 1, mid)
cnt[d] += 1
# every digit set whose digit sum (= length) is at most 17 and has at most one odd digit
for mask in range(1, 512):
digits = [d for d in range(1, 10) if mask >> (d - 1) & 1]
total = sum(digits)
odds = [d for d in digits if d % 2]
if total > 17 or len(odds) > 1:
continue
for d in digits:
cnt[d] = d // 2
build("", total // 2, str(odds[0]) if odds else "")
for d in digits:
cnt[d] = 0
return best