Break a Palindrome — LeetCode 1328 Python Solution

MediumGreedyString
Problem
#1328
Pattern
Greedy
Reading time
3 min

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

Example

Input
palindrome = "abccba"
Output
"aaccba"
Explanation
There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba".

Python solution

Python
class Solution:
    def breakPalindrome(self, palindrome: str) -> str:
        n = len(palindrome)
        if n == 1:
            return ""
        s = list(palindrome)
        i = 0
        while i < n // 2 and s[i] == "a":
            i += 1
        if i == n // 2:
            s[-1] = "b"
        else:
            s[i] = "a"
        return "".join(s)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1328. Break a Palindrome is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1328. Break a Palindrome?
LeetCode 1328. Break a Palindrome is rated Medium on LeetCode.
What is the time complexity of LeetCode 1328. Break a Palindrome?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1328. Break a Palindrome?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1328. Break a Palindrome cover?
LeetCode 1328. Break a Palindrome is tagged Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview