#1328
Medium Algorithms Break a palindrome
String Greedy
51.6% acceptance
Feb 25, 2026
2436
754
Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.
Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.
A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, "abcc" is lexicographically smaller than "abcd" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn break_palindrome(palindrome: String) -> String {
let n = palindrome.len();
if n == 1 { return String::new(); }
let mut chars: Vec<u8> = palindrome.into_bytes();
// Find the first non-'a' in the first half to replace with 'a'
for i in 0..n / 2 {
if chars[i] != b'a' {
chars[i] = b'a';
return String::from_utf8(chars).unwrap();
}
}
// All characters are 'a' (or middle char), replace last with 'b'
*chars.last_mut().unwrap() = b'b';
String::from_utf8(chars).unwrap()
}
}