Problem 1328

Abstract / Summary

Change one character in the middle of a palindrome to any other letter to make it not a palindrome

Note

The full problem description, including helpful examples, can be found on LeetCode.

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"
18 lines | 592 bytes | submitted January 9, 2024 | GitHub   36% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (300k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.93 | σ = 0.98

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
25 links | 13 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   January 9, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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