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
๐Ÿญ Palindrome Mirror FactoryInput MachineQuery: k=4Length: 3Processing...CalculatorFirst half = 2Start = 10Result = 13Mirror Machine13 โ†’ 1|3|1Mirror centerOutput: 131131โœ“ ValidPalindromeProduction Statisticsโ€ข Length 1: 9 palindromes (1-9)โ€ข Length 2: 9 palindromes (11, 22, 33, ..., 99)โ€ข Length 3: 90 palindromes (101, 111, ..., 191, 202, ...)โ€ข Pattern: 9 ร— 10^((length-1)/2) palindromes131Mirror Symmetry
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!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.2K Views
Medium-High Frequency
~18 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen