Leetcode #2217: Find Palindrome With Fixed Length
In this guide, we solve Leetcode #2217 Find Palindrome With Fixed Length in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Math
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
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.
Python Solution
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
Complexity
The time complexity is O(n) or O(1). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.