Find Palindrome With Fixed Length - Problem
Imagine you're building a special number generator that creates palindromic numbers - numbers that read the same forwards and backwards, like 121 or 12321.
Given an array of queries and a fixed intLength, you need to find the k-th smallest palindrome of exactly intLength digits for each query k.
Key Rules:
- Palindromes cannot have leading zeros (so 010 is invalid)
- If the k-th palindrome doesn't exist, return -1
- Each query asks for a different position in the sequence of valid palindromes
Example: For length 3, valid palindromes are: 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, ...
Input & Output
example_1.py โ Basic Query
$
Input:
queries = [1, 2, 3, 4, 90, 91], intLength = 3
โบ
Output:
[101, 111, 121, 131, 191, 202]
๐ก Note:
For 3-digit palindromes: 1st=101, 2nd=111, 3rd=121, 4th=131, 90th=191, 91st=202. All queries have valid palindromes.
example_2.py โ Invalid Query
$
Input:
queries = [2, 4, 6], intLength = 4
โบ
Output:
[1001, 1111, 1221]
๐ก Note:
For 4-digit palindromes: 1st=1001, 2nd=1001, 3rd=1111, 4th=1111, 5th=1221, 6th=1221. The 2nd, 4th, and 6th palindromes are valid.
example_3.py โ Edge Case
$
Input:
queries = [1, 2, 3, 4, 5, 90], intLength = 1
โบ
Output:
[1, 2, 3, 4, 5, -1]
๐ก Note:
Single-digit palindromes are 1,2,3,4,5,6,7,8,9. Only 9 exist, so query 90 returns -1.
Constraints
- 1 โค queries.length โค 5 ร 104
- 1 โค queries[i] โค 109
- 1 โค intLength โค 15
- Palindromes cannot have leading zeros
Visualization
Tap to expand
Understanding the Visualization
1
Setup Production Line
Calculate total capacity: for length 3, we can make 90 palindromes (first half: 10-99)
2
Find Template Number
For k-th palindrome, calculate first half: start + (k-1)
3
Apply Mirror Process
Create full palindrome by mirroring the first half
4
Quality Check
Verify no leading zeros and correct length
Key Takeaway
๐ฏ Key Insight: Since palindromes are symmetric, we only need to determine the first half - the factory can automatically mirror it to create the complete palindrome in constant time!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code