Break a Palindrome - Problem

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'.

Input & Output

Example 1 — Replace First Non-'a'
$ Input: palindrome = "abccba"
Output: "aaccba"
💡 Note: The first non-'a' character is 'b' at position 1. Replace it with 'a' to get "aaccba", which is not a palindrome and lexicographically smallest.
Example 2 — All Characters Are 'a'
$ Input: palindrome = "aa"
Output: "ab"
💡 Note: All characters are 'a', so we change the last character to 'b' to get "ab", which breaks the palindrome.
Example 3 — Single Character
$ Input: palindrome = "a"
Output: ""
💡 Note: Cannot break a single character palindrome while maintaining the same length, so return empty string.

Constraints

  • 1 ≤ palindrome.length ≤ 1000
  • palindrome consists of only lowercase English letters
  • palindrome is a palindrome

Visualization

Tap to expand
Break a Palindrome: Find Lexicographically Smallest Non-PalindromeStep 1: Input PalindromeracecarStep 2: Replace First Non-'a' with 'a'Replace 'r' → 'a'Step 3: Result (Non-palindrome)aacecar"aacecar" ≠ "racecar" (palindrome broken)Lexicographically smallest possible!
Understanding the Visualization
1
Input
Palindromic string like "racecar"
2
Process
Find first non-'a' character and replace with 'a'
3
Output
Lexicographically smallest non-palindrome "aacecar"
Key Takeaway
🎯 Key Insight: To get the lexicographically smallest result, replace the first non-'a' character with 'a', or if all are 'a', change the last to 'b'
Asked in
Facebook 15 Amazon 12 Google 8 Microsoft 6
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen