Find the Largest Palindrome Divisible by K Problem
Description
LeetCode Problem 3260.
You are given two positive integers n and k.
An integer x is called k-palindromic if:
xis a palindrome.xis divisible byk.
Return the largest integer having n digits (as a string) that is k-palindromic.
Note that the integer must not have leading zeros.
Example 1:
Input: n = 3, k = 5
Output: "595"
Explanation:
595 is the largest k-palindromic integer with 3 digits.
Example 2:
Input: n = 1, k = 4
Output: "8"
Explanation:
4 and 8 are the only k-palindromic integers with 1 digit.
Example 3:
Input: n = 5, k = 6
Output: "89898"
Constraints:
1 <= n <= 10^51 <= k <= 9
Solution
Approach: Greedy + Reachability DP on the First Half
A palindrome is determined by its first half of h = ceil(n / 2) digits. Position i of the half contributes d_i * w_i to the number modulo k, where w_i = (10^i + 10^(n-1-i)) mod k (just 10^i for the middle digit of an odd length).
Compute f[i][r]: can digits i..h-1 be chosen so that their weighted sum is r modulo k? Fill it from the back, trying all ten digits per cell. Then build the answer from the front: at each position pick the largest digit (at least 1 for the first position) such that the remaining positions can still reach the required remainder. Mirror the half to get the whole palindrome. Since k <= 9, the table is only about 9 * n / 2 cells.
Complexity: O(n * k * 10) time and O(n * k) space.
class Solution:
def largestPalindrome(self, n: int, k: int) -> str:
h = (n + 1) // 2
p = [1 % k] * n
for i in range(1, n):
p[i] = p[i - 1] * 10 % k
w = [(p[i] + p[n - 1 - i]) % k if i != n - 1 - i else p[i] for i in range(h)]
f = [[False] * k for _ in range(h + 1)]
f[h][0] = True
for i in range(h - 1, -1, -1):
for r in range(k):
for d in range(10):
if f[i + 1][(r + 9 * k - d * w[i]) % k]:
f[i][r] = True
break
rem = 0
half = []
for i in range(h):
for d in range(9, -1, -1):
if i == 0 and d == 0:
continue
nxt = (rem + 9 * k - d * w[i]) % k
if f[i + 1][nxt]:
half.append(str(d))
rem = nxt
break
s = "".join(half)
return s + s[: n // 2][::-1]