Break a Palindrome - Problem

You're given a palindromic string of lowercase English letters. Your mission is to break the palindrome by replacing exactly one character with any lowercase English letter, creating a string that is:

  • Not a palindrome
  • Lexicographically smallest possible

If it's impossible to break the palindrome (hint: think about single characters!), return an empty string.

Lexicographical order: String a comes before string b if at the first differing position, a has a smaller character. For example, "abcc" < "abcd" because 'c' < 'd' at position 3.

Example: "abccba""aaccba" (replace first 'b' with 'a')

Input & Output

example_1.py — Basic Case
$ Input: palindrome = "abccba"
Output: "aaccba"
💡 Note: We can change the first 'b' to 'a' to get "aaccba", which is not a palindrome and is lexicographically smallest among all possible changes.
example_2.py — All Same Characters
$ Input: palindrome = "aa"
Output: "ab"
💡 Note: Since the first half contains only 'a', we change the last character from 'a' to 'b' to break the palindrome while keeping it lexicographically smallest.
example_3.py — Single Character
$ Input: palindrome = "a"
Output: ""
💡 Note: It's impossible to break a single character palindrome by changing exactly one character, so we return an empty string.

Visualization

Tap to expand
🏭 Breaking the Mirror Word FactoryGreedy Strategy: Make the earliest, smallest change possiblea✓ Keepb→ acMirror LinecbaFirst non-'a'!💡 Key InsightTo get lexicographically smallest result:1. Change as early (leftmost) as possible2. Change to smallest character ('a')
Understanding the Visualization
1
Scan from Left
Start from the leftmost position to ensure lexicographically smallest result
2
Find First Non-'a'
Look for the first character that isn't 'a' in the first half
3
Change to 'a'
Replace it with 'a' to get the smallest possible character
4
Fallback Strategy
If first half is all 'a', change last character to 'b'
Key Takeaway
🎯 Key Insight: The greedy approach works because changing the leftmost non-'a' character to 'a' always produces the lexicographically smallest valid result. This leverages the palindrome property efficiently!

Time & Space Complexity

Time Complexity
⏱️
O(n²)

For each of n positions, we try 26 letters and check if result is palindrome (O(n)), giving us O(n × 26 × n) = O(n²)

n
2n
Quadratic Growth
Space Complexity
O(n)

We create new strings for each attempt, each taking O(n) space

n
2n
Linearithmic Space

Constraints

  • 1 ≤ palindrome.length ≤ 1000
  • palindrome consists of only lowercase English letters
  • palindrome is guaranteed to be a valid palindrome
Asked in
Amazon 45 Google 32 Meta 28 Microsoft 22
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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