Break a Palindrome Problem
Description
LeetCode Problem 1328.
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. If there is no way to replace a character to make it not a palindrome, return an empty string.
A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, "abcc" is lexicographically smaller than "abcd" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.
Example 1:
Input: palindrome = "abccba"
Output: "aaccba"
Explanation: There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba".
Of all the ways, "aaccba" is the lexicographically smallest.
Example 2:
Input: palindrome = "a"
Output: ""
Explanation: There is no way to replace a single character to make "a" not a palindrome, so return an empty string.
Constraints:
1 <= palindrome.length <= 1000palindromeconsists of only lowercase English letters.
Solution
Approach: Greedy
To get the lexicographically smallest result, we want to make an earlier character smaller, and as small as possible, which means turning it into 'a'.
So we look for the first character that is not 'a', but only in the first half of the string. In the second half, every character mirrors one in the first half, so if the first half is all 'a', so is the second. The middle character of an odd-length string must be skipped: changing it keeps the string a palindrome ("aba" to "aaa").
- If the first half has a character other than
'a', change the first one to'a'. Its mirror stays the same, so the string is no longer a palindrome. - If the first half is all
'a', any change has to make some character bigger. The cheapest way is to change the last character to'b', as late as possible and by as little as possible ("aba"becomes"abb").
The one case with no answer is a string of length 1: whatever we change it to, a single letter is still a palindrome, so we return "".
Complexity: O(n) time, and O(n) space for the modified copy of the string.
class Solution:
def breakPalindrome(self, palindrome: str) -> str:
n = len(palindrome)
if n == 1:
return "" # changing the only letter still leaves a palindrome
s = list(palindrome)
for i in range(n // 2): # the middle letter of an odd length would not help
if s[i] != "a":
s[i] = "a"
return "".join(s)
s[-1] = "b" # the first half is all 'a': make the last letter as small as possible
return "".join(s)