Find Palindrome With Fixed Length — LeetCode 2217 Python Solution
- Problem
- #2217
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
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:
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2217. Find Palindrome With Fixed Length is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2217. Find Palindrome With Fixed Length?
- LeetCode 2217. Find Palindrome With Fixed Length is rated Medium on LeetCode.
- What topics does LeetCode 2217. Find Palindrome With Fixed Length cover?
- LeetCode 2217. Find Palindrome With Fixed Length is tagged Array and Math on LeetCode.