#906
Hard Algorithms Super palindromes
Math String Enumeration
39.8% acceptance
Feb 25, 2026
376
423
Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn superpalindromes_in_range(left: String, right: String) -> i32 {
let lo: i64 = left.parse().unwrap();
let hi: i64 = right.parse().unwrap();
let mut count = 0;
let is_pal = |s: &str| -> bool { s.as_bytes() == s.as_bytes().iter().rev().cloned().collect::<Vec<u8>>() };
// Odd-length palindromes: k -> k + reverse(k without last digit)
for k in 1..100_001i64 {
let s = k.to_string();
let rev: String = s[..s.len()-1].chars().rev().collect();
let p: i64 = format!("{}{}", s, rev).parse().unwrap();
let p2 = p * p;
if p2 > hi { break; }
if p2 >= lo && is_pal(&p2.to_string()) { count += 1; }
}
// Even-length palindromes: k -> k + reverse(k)
for k in 1..100_001i64 {
let s = k.to_string();
let rev: String = s.chars().rev().collect();
let p: i64 = format!("{}{}", s, rev).parse().unwrap();
let p2 = p * p;
if p2 > hi { break; }
if p2 >= lo && is_pal(&p2.to_string()) { count += 1; }
}
count
}
}