Skip to main content
Back to problems
#2217
Medium Algorithms

Find palindrome with fixed length

Array Math
37.9% acceptance
Feb 25, 2026
663
296
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn kth_palindrome(queries: Vec<i32>, int_length: i32) -> Vec<i64> {
    let half_len = ((int_length + 1) / 2) as u32;
    let start = 10i64.pow(half_len - 1);
    let end = 10i64.pow(half_len);
    queries.iter().map(|&q| {
      let half = start + q as i64 - 1;
      if half >= end { return -1i64; }
      let s = half.to_string();
      let right: String = if int_length % 2 == 0 {
        s.chars().rev().collect()
      } else {
        s[..half_len as usize - 1].chars().rev().collect()
      };
      format!("{}{}", s, right).parse::<i64>().unwrap()
    }).collect()
  }
}