Python 1328.py
class Solution:
def breakPalindrome(self, palindrome: str) -> str:
# always palindrome
if len(palindrome) == 1:
return ""
# don't replace "a" if in the middle (=> will still be a palindrome)
mid = -1
if len(palindrome) & 1:
mid = len(palindrome) // 2
# look for first position which isn't "a"
for i, c in enumerate(palindrome):
if c > "a" and i != mid:
return palindrome[:i] + "a" + palindrome[i + 1:]
# only "a"s
return palindrome[:-1] + "b"
Difficulty
and has an acceptance rate of about 52% (300k+ submissions).
Typical patterns to solve this problem:
- Greedy
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method that transforms a given palindrome string into the lexicographically smallest non-palindromic string by changing exactly one character. The algorithm works in a single linear scan, handling special cases such as single-character inputs and strings composed entirely of the character 'a'. Early returns are used to avoid unnecessary work, and string slicing is performed only when a modification is required.
Input validation and single-character handling
if len(palindrome) == 1:
return ""
When the input length is one, any change would either produce the same character (still a palindrome) or an empty string, which is defined as the correct result. This guard prevents further processing on an input that cannot be altered to meet the problem constraints.
Determining the middle index for odd-length strings
mid = -1
if len(palindrome) & 1:
mid = len(palindrome) // 2
For odd-length palindromes, the central character can be changed without breaking the palindrome property because it mirrors itself. By storing the middle index in mid, the algorithm can later skip this position when searching for a character to replace, ensuring that the modification actually disrupts the symmetry.
Searching for the first replaceable character
for i, c in enumerate(palindrome):
if c > "a" and i != mid:
return palindrome[:i] + "a" + palindrome[i + 1:]
The loop iterates over each character together with its index. The condition c > "a" identifies the first character that is not already the smallest possible letter 'a'. By also checking i != mid, the algorithm avoids altering the middle character of an odd-length palindrome, which would leave the string unchanged in terms of palindrome status. When such a character is found, it is replaced with 'a' using slice concatenation, and the resulting string is returned immediately. This early exit guarantees that only the minimal necessary work is performed.
Handling the all-'a' case
return palindrome[:-1] + "b"
If the loop completes without finding a character greater than 'a', the input consists solely of 'a' characters. Changing any interior 'a' to another letter would still produce a palindrome, so the algorithm replaces the last character with 'b'. This yields the smallest lexicographic non-palindromic string possible under the constraints, and it does so with a single slice operation.
Edge-case coverage
The method explicitly addresses three distinct edge conditions:
- A palindrome of length one returns an empty string, as no valid single-character change can break the palindrome.
- For odd-length inputs, the central character is excluded from replacement candidates, preventing a no-op change that would preserve the palindrome.
- When the entire string is composed of
'a', the algorithm substitutes the final character with'b', ensuring the result is no longer a palindrome while remaining lexicographically minimal.
Each of these scenarios is resolved without resorting to additional loops or conditional branches beyond those shown.
Performance optimizations
The implementation achieves efficiency through several deliberate choices. The early return for single-character inputs eliminates unnecessary work for the smallest possible input. The use of a bitwise AND (len(palindrome) & 1) to test odd length is a constant-time operation. The main loop performs a single pass over the string, stopping at the first viable replacement, which means the average number of examined characters is low for typical inputs. String reconstruction occurs only once, either when a non-'a' character is found or in the final fallback case, minimizing the overhead of creating intermediate strings. By avoiding any auxiliary data structures and relying on direct indexing and slicing, the method maintains a low memory footprint while delivering the required transformation in linear time.
ELI5 - Simplified Explanation
Imagine you have a row of colored blocks that spell out a word which reads the same forward and backward, like a mirror image. The goal is to change just one letter to make it not mirror anymore, keeping the word as small as possible.
First, look at the length of the string. If there is only one block, nothing can be changed to stop it from being a palindrome, so it disappears.
When there is a middle spot, like the center bead on a necklace, changing that would not break the mirror pattern. So, the search skips that exact middle position.
Moving along the row from left to right, look for the first letter that is not an a. Since a is the smallest letter, changing that letter to an a makes the word smaller and breaks the mirror, which is exactly what is needed.
If the whole row is already filled with only a characters, changing any of them to another a would not do anything. Instead, change the very last letter to a b. This makes the word different while keeping it as small as possible.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | TS | |||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java |
Videos
Solved On The Same Day
- problem 1370: Increasing Decreasing String
- problem 1380: Lucky Numbers in a Matrix
- problem 1310: XOR Queries of a Subarray
- problem 1343: Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality