#2384
Medium Algorithms Largest palindromic number
Hash Table String Greedy Counting
37.0% acceptance
Feb 25, 2026
669
238
You are given a string num consisting of digits only.
Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes.
Notes:
You do not need to use all the digits of num, but you must use at least one digit.
The digits can be reordered.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn largest_palindromic(num: String) -> String {
let mut freq = [0usize; 10];
for c in num.bytes() { freq[(c - b'0') as usize] += 1; }
let mut half: Vec<u8> = vec![];
for d in (1..=9usize).rev() {
for _ in 0..freq[d]/2 { half.push(b'0' + d as u8); }
}
if !half.is_empty() {
for _ in 0..freq[0]/2 { half.push(b'0'); }
}
let middle = (0..=9usize).rev().find(|&d| freq[d] % 2 == 1).map(|d| b'0' + d as u8);
if half.is_empty() {
return String::from_utf8(vec![middle.unwrap_or(b'0')]).unwrap();
}
let mut result = half.clone();
if let Some(m) = middle { result.push(m); }
for &b in half.iter().rev() { result.push(b); }
String::from_utf8(result).unwrap()
}
}