Problem Description
Given two positive integers n and k, find the largest n‑digit integer (returned as a string) that is both a palindrome and divisible by k. The palindrome must not have leading zeros.
Key Insights
- A palindrome of n digits is determined completely by its first half (and the middle digit if n is odd).
- For even n, if we denote the first half as a string a, the full palindrome is formed as a + reverse(a). For odd n, if a is the first half (including the middle digit), the full palindrome is a[0:len(a)-1] + reverse(a).
- We need to ensure that the constructed n‑digit palindrome, when interpreted as an integer, is divisible by k.
- Since k is small (1 ≤ k ≤ 9) we can use modular arithmetic in our DP state.
- A greedy–DP (backtracking) approach is used: process the “controlling” half digit by digit in descending order (from the most significant digit) and choose the highest possible digit at each step that can still lead to a solution.
Space and Time Complexity
Time Complexity: O(n * k * 10) in the worst case, since we fill about ceil(n/2) positions with 10 choices each and our DP state has at most O(n * k) states. Space Complexity: O(n * k) for the DP memoization table and O(n) for storing the resulting palindrome.
Solution
We observe that any n-digit palindrome is completely determined by its first half (if n is even) or the first half including the middle digit (if n is odd). Therefore we define: • L = n/2 for even n, and L = n//2 for the “left part” plus one extra digit (the middle) for odd n. • For each of the positions in the “controlling” half, the digit we choose contributes twice (once for its original place and once for its mirror) except for the middle digit when n is odd, which contributes only once. • We precompute the modular weight of each chosen digit position using the fact that for a digit placed at index i (0-indexed from the left in the full n‑digit palindrome) its contribution is digit * 10^(n-i-1) mod k. In the symmetric positions the contributions sum up. • With the modular weights computed for each “decision position” the problem reduces to picking digits (using DP/backtracking with memoization) for these positions so that the total contribution (mod k) equals 0. • A greedy approach is applied: at each position, try to assign the largest valid digit (taking care to avoid 0 at the first position) and check (via recursion with memoization) if a solution can be found for the remaining positions for the required remainder. • Finally, using the chosen half we mirror it appropriately (excluding the middle digit for odd n) to obtain the full palindrome.