Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
Example 1:
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: 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ... The 90th palindrome of length 3 is 999.
Example 2:
Input: queries = [2,4,6], intLength = 4 Output: [1111,1331,1551] Explanation: The first six palindromes of length 4 are: 1001, 1111, 1221, 1331, 1441, and 1551.
Constraints:
1 <= queries.length <= 5 * 1041 <= queries[i] <= 1091 <= intLength <= 15Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math
[1,2,3,4,5,90] 3
[2,4,6] 4
palindrome-number)find-the-closest-palindrome)lexicographically-smallest-beautiful-string)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2217: Find Palindrome With Fixed Length
class Solution {
public long[] kthPalindrome(int[] queries, int intLength) {
int n = queries.length;
long[] ans = new long[n];
int l = (intLength + 1) >> 1;
long start = (long) Math.pow(10, l - 1);
long end = (long) Math.pow(10, l) - 1;
for (int i = 0; i < n; ++i) {
long v = start + queries[i] - 1;
if (v > end) {
ans[i] = -1;
continue;
}
String s = "" + v;
s += new StringBuilder(s).reverse().substring(intLength % 2);
ans[i] = Long.parseLong(s);
}
return ans;
}
}
// Accepted solution for LeetCode #2217: Find Palindrome With Fixed Length
func kthPalindrome(queries []int, intLength int) []int64 {
l := (intLength + 1) >> 1
start, end := int(math.Pow10(l-1)), int(math.Pow10(l))-1
var ans []int64
for _, q := range queries {
v := start + q - 1
if v > end {
ans = append(ans, -1)
continue
}
t := v
if intLength%2 == 1 {
t /= 10
}
for t > 0 {
v = v*10 + t%10
t /= 10
}
ans = append(ans, int64(v))
}
return ans
}
# Accepted solution for LeetCode #2217: Find Palindrome With Fixed Length
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
// Accepted solution for LeetCode #2217: Find Palindrome With Fixed Length
impl Solution {
pub fn kth_palindrome(queries: Vec<i32>, int_length: i32) -> Vec<i64> {
let is_odd = (int_length & 1) == 1;
let best_num = i32::pow(10, (int_length / 2 + (if is_odd { 0 } else { -1 })) as u32);
let max = best_num * 9;
queries
.iter()
.map(|&num| {
if num > max {
return -1;
}
let num = best_num + num - 1;
format!(
"{}{}",
num,
num.to_string()
.chars()
.rev()
.skip(if is_odd { 1 } else { 0 })
.collect::<String>()
)
.parse()
.unwrap()
})
.collect()
}
}
// Accepted solution for LeetCode #2217: Find Palindrome With Fixed Length
function kthPalindrome(queries: number[], intLength: number): number[] {
const isOdd = intLength % 2 === 1;
const bestNum = 10 ** ((intLength >> 1) + (isOdd ? 1 : 0) - 1);
const max = bestNum * 9;
return queries.map(v => {
if (v > max) {
return -1;
}
const num = bestNum + v - 1;
return Number(
num +
(num + '')
.split('')
.reverse()
.slice(isOdd ? 1 : 0)
.join(''),
);
});
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.