Find Palindrome With Fixed Length - 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. Palindromes cannot have leading zeros.

Input & Output

Example 1 — Basic Case
$ Input: queries = [1,2,3,4,5,90], intLength = 3
Output: [101,111,121,131,141,999]
💡 Note: For length 3: 1st palindrome is 101, 2nd is 111, 3rd is 121, etc. The 90th palindrome is 999.
Example 2 — Out of Range
$ Input: queries = [2,4,6], intLength = 4
Output: [1001,1111,1221]
💡 Note: For length 4: palindromes are 1001, 1111, 1221, 1331, etc.
Example 3 — Single Digit
$ Input: queries = [1,2,3,4,5,6,7,8,9,10], intLength = 1
Output: [1,2,3,4,5,6,7,8,9,-1]
💡 Note: For length 1: only 9 palindromes exist (1-9), so query 10 returns -1

Constraints

  • 1 ≤ queries.length ≤ 5 × 104
  • 1 ≤ queries[i] ≤ 109
  • 1 ≤ intLength ≤ 15

Visualization

Tap to expand
Find Palindrome With Fixed Length INPUT queries array: 1 2 3 4 5 90 intLength: 3 3-digit palindrome structure: d1 d2 d1 First = Last digit Middle varies freely Range: 101 to 999 ALGORITHM STEPS 1 Calculate Half Length half = (3+1)/2 = 2 digits 2 Find Base Number base = 10^(2-1) = 10 3 Compute First Half firstHalf = base + query - 1 4 Mirror to Palindrome Reverse first half, append Example: query=1 firstHalf = 10 + 1 - 1 = 10 Take "10", reverse = "01" Skip middle: use "1" "10" + reverse("1") = "101" Result: 101 FINAL RESULT Query to Palindrome Mapping: Query FirstHalf Result 1 10 101 2 11 111 3 12 121 4 13 131 5 14 141 90 99 999 Output Array: [101,111,121,131,141,999] OK - All Valid! Total 3-digit palindromes: 90 (from 101 to 999) Key Insight: For a palindrome of length L, only the first half matters! The second half is just a mirror. The Nth palindrome = (base + N - 1) mirrored, where base = 10^(halfLen-1). This gives O(1) lookup per query instead of generating all palindromes. Time: O(Q * L), Space: O(L). TutorialsPoint - Find Palindrome With Fixed Length | Optimal Solution
Asked in
Google 15 Meta 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
485 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