Find Palindrome With Fixed Length Problem
Description
LeetCode Problem 2217.
Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]^th smallest positive palindrome of length intLength or -1 if no such palindrome exists.
A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.
Example 1:
Input: queries = [1,2,3,4,5,90], intLength = 3
Output: [101,111,121,131,141,999]
Explanation:
The first few palindromes of length 3 are:
101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...
The 90^th palindrome of length 3 is 999.
Example 2:
Input: queries = [2,4,6], intLength = 4
Output: [1111,1331,1551]
Explanation:
The first six palindromes of length 4 are:
1001, 1111, 1221, 1331, 1441, and 1551.
Constraints:
1 <= queries.length <= 5 * 10^41 <= queries[i] <= 10^91 <= intLength <= 15
Solution
Approach: Build From the First Half
A palindrome is fixed by its first half, and the second half is the mirror image. For intLength = L, the first half has h = ceil(L / 2) digits and cannot start with 0, so there are exactly 9 · 10^(h-1) palindromes of that length, and they are ordered the same way as their first halves.
So the q-th palindrome has first half 10^(h-1) + q - 1. If that exceeds 10^h - 1 the answer is -1. Otherwise write the half as a string and append its reverse, skipping the first reversed digit when L is odd (the middle digit is not repeated).
Complexity: O(n · L) time for n queries and O(L) extra space.
class Solution:
def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:
l = (intLength + 1) >> 1
start, end = 10 ** (l - 1), 10**l - 1
ans = []
for q in queries:
v = start + q - 1
if v > end:
ans.append(-1)
continue
s = str(v)
s += s[::-1][intLength % 2 :]
ans.append(int(s))
return ans