#1328
Break a Palindrome
MediumStringGreedyGreedyTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach focuses on the fact that we can make the smallest lexicographical change by changing the first non-'a' character to 'a', or the last character to 'b' if all are 'a'. This avoids unnecessary checks and is efficient.
⚙️
Algorithm
4 steps- 1Step 1: If the length of the string is 1, return an empty string.
- 2Step 2: Iterate through the string until the middle (or the end for even lengths).
- 3Step 3: If a character is found that is not 'a', change it to 'a' and return the modified string.
- 4Step 4: If all characters are 'a', change the last character to 'b' and return the modified string.
solution.py10 lines
1# Full working Python code
2
3def breakPalindrome(palindrome):
4 if len(palindrome) == 1:
5 return ""
6 n = len(palindrome)
7 for i in range(n // 2):
8 if palindrome[i] != 'a':
9 return palindrome[:i] + 'a' + palindrome[i + 1:]
10 return palindrome[:-1] + 'b' # Change last character to 'b'ℹ
Complexity note: This complexity is linear because we only traverse half of the string to find the first non-'a' character, and we make a single modification, which is efficient.
- 1Changing the first non-'a' character to 'a' gives the smallest lexicographical result.
- 2If all characters are 'a', changing the last character to 'b' is the only option.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.