Break a Palindrome (LeetCode 1328): Solution and Explanation

Medium
String
Greedy

Change exactly one character of a palindrome so that it is no longer a palindrome and is as small as possible in dictionary order. Return "" if that cannot be done.

Intuition

Dictionary order is decided by the first position where two strings differ. So the best move is to make the earliest position you can as small as possible, and the smallest letter is 'a'.

In a palindrome every left-half character is tied to its mirror on the right. Changing a left-half character to something different breaks that pair, so the result is guaranteed not to be a palindrome. The middle character of an odd-length string is its own mirror, so changing it does nothing to break the symmetry.

If every left-half character is already 'a', nothing can be made smaller. Then the least harmful change is to raise the very last character, and the smallest raise is to 'b'.

Approach: Greedy on the left half

  1. If the string has length 1, return "".
  2. Scan indices 0 to n/2 - 1. At the first character that is not 'a', replace it with 'a' and return the string.
  3. If the scan finishes, every left-half character is 'a'. Replace the last character with 'b' and return the string.

Step-by-step example

palindrome = "abccba"
  1. n = 6, so the left half is indices 0, 1, 2.
  2. Index 0 is 'a'. It is already the smallest letter, so move on.
  3. Index 1 is 'b'. Change it to 'a'; its mirror at index 4 is still 'b', so the string is no longer a palindrome.
  4. Return "aaccba".

Code: Python, Java, C++

1class Solution:
2    def breakPalindrome(self, palindrome: str) -> str:
3        n = len(palindrome)
4        if n == 1:
5            return ""
6        chars = list(palindrome)
7        for i in range(n // 2):
8            if chars[i] != 'a':
9                chars[i] = 'a'
10                return "".join(chars)
11        chars[-1] = 'b'
12        return "".join(chars)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

At most half the string is scanned, and building the result is linear.

Space

O(n)

Strings are immutable in most languages, so the answer needs a mutable copy of the characters.

Other approaches

Try every replacement (time O(26 n^2), space O(n))

For each position and each of the 26 letters, build the new string, check that it is not a palindrome, and keep the smallest. Correct but does O(26 * n^2) work.

Common mistakes

  • Changing the middle character of an odd-length string. "aba" becomes "aaa", which is still a palindrome. Only scan the left half.
  • Scanning the whole string for a non-'a'. In "aabaa" the only non-'a' is the middle, and changing it would not break the palindrome.
  • Forgetting the all-'a' case, where the answer is to set the last character to 'b', not the first.
  • Returning the original string or "a" for length 1 instead of the empty string.

Frequently asked questions

Why change the last character to 'b' and not the first?

Changing an early character to 'b' makes the string bigger at an early position. Changing the last one only affects the final position, so the result stays as small as possible.

Why is the left half enough to scan?

The right half mirrors the left half, so any right-half character has the same letter earlier in the string. Changing the earlier copy always gives a smaller result.

Can the answer ever be the same length palindrome again?

No. Every change made by this method touches a character whose mirror stays the same, so the pair no longer matches.

What are the time and space costs?

O(n) time for at most one pass, and O(n) space for the character copy.