Problem Description
Given an integer array queries and a positive integer intLength, find the queries[i]th smallest positive palindrome of length intLength for each query. If the query is greater than the number of palindromes of that fixed length, return -1 for that query. A palindrome reads the same backwards and forwards, and palindromic numbers must not have leading zeros.
Key Insights
- The palindrome can be constructed from a prefix (first half of the number). For an odd intLength, the middle digit is shared.
- The number of valid palindromes is determined by the range of valid first-half numbers. The starting prefix is 10^(half-1) (to avoid leading zeros) and the count is 9 * 10^(half-1).
- For each query, if the query index exceeds the count of available prefixes, return -1.
- Convert the prefix into a palindrome by mirroring it appropriately depending on whether the intLength is even or odd.
Space and Time Complexity
Time Complexity: O(q * p) where q is the number of queries and p is the number of digits in the prefix (at most 8 given constraints), which is efficient for q up to 5 * 10^4. Space Complexity: O(q) to store the resulting palindrome for each query.
Solution
The solution involves generating palindromic numbers using the following steps:
- Determine half the length needed to build the palindrome. If intLength is odd, let half = (intLength + 1) // 2; otherwise, half = intLength // 2.
- Compute the starting prefix as start = 10^(half - 1) and the maximum number of prefixes as count = 9 * 10^(half - 1).
- For each query, check if the query's value is more than count. If so, return -1.
- Otherwise, calculate the prefix number by adding (query - 1) to the starting prefix.
- Convert the prefix to a string to build the final palindrome:
- For even intLength: Concatenate prefix string with its reverse.
- For odd intLength: Concatenate prefix string with the reverse of the prefix string excluding the last character.
- Append the computed palindrome (as an integer) to the answer list.
The main trick is realizing that the queries correspond directly to the order of the first-half prefixes.