Given an integer array queries and a positive integer intLength, return an arrayanswerwhereanswer[i]is either the queries[i]thsmallest positive palindrome of lengthintLengthor-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 90th 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 * 104
1 <= queries[i] <= 109
1 <= intLength <= 15
Solutions
Solution 1
Thinking
We need the \(q\)-th palindrome of length \(\textit{intLength}\). \(q\) can be \(10^9\) and the length up to \(15\), so listing palindromes is impossible. A palindrome is determined by its first half; the second half is the mirror.
The first half has length \(\lceil \textit{intLength}/2 \rceil\) and ranges from \(10^{l-1}\) to \(10^l-1\). Query \(q\) maps to \(v = 10^{l-1}+q-1\); if \(v\) overflows the answer is \(-1\), otherwise mirror \(v\)'s digits (dropping the middle copy when the length is odd).