Skip to main content
Back to problems
#479
Hard Algorithms

Largest palindrome product

Math Enumeration
38.1% acceptance
Jan 13, 2026
193
1569
Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn largest_palindrome(n: i32) -> i32 {
    if n == 1 {
      return 9;
    }
    
    let max = 10_i64.pow(n as u32) - 1;
    let min = 10_i64.pow((n - 1) as u32);
    
    for i in (min..=max).rev() {
      let s = i.to_string();
      let palindrome = format!("{}{}", s, s.chars().rev().collect::<String>());
      let pal_num = palindrome.parse::<i64>().unwrap();
      
      for j in (min..=max).rev() {
        if j * j < pal_num {
          break;
        }
        if pal_num % j == 0 {
          let other = pal_num / j;
          if other >= min && other <= max {
            return (pal_num % 1337) as i32;
          }
        }
      }
    }
    
    -1
  }
}