Find Palindrome With Fixed Length — LeetCode 2217 Python Solution

MediumArrayMath
Problem
#2217
Reading time
3 min

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

Python
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

MeasureComplexity
TimeO(n) or O(1)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview