Break a Palindrome — LeetCode 1328 Python Solution
- Problem
- #1328
- Pattern
- Greedy
- Reading time
- 3 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.