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 <= 1000palindrome consists of only lowercase English letters.In this approach, we iterate through the first half of the string and try to replace the first non-'a' character with 'a'. This ensures that we're making the lexicographically smallest change as early as possible in the string. If we can't find a character that is not 'a' in the first half, we replace the last character with 'b' to ensure it's not a palindrome.
This C code checks each character in the first half of the string and replaces the first non-'a' character with 'a'. If no such character is found, it makes the last character 'b'.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
This approach focuses on changing the center character if possible, because altering the center in an odd-length palindrome often results in a non-palindrome quickly. For even lengths, alterations must be controlled to preserve lexicographical order.
Focuses on odd-length palindrome to modify the center character, transforming it to 'a' if possible, ensuring not a palindrome.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Approach 1: Try to Replace with 'a' Early | Time Complexity: O(n) |
| Approach 2: Modify Center Character | Time Complexity: O(n) |
Leetcode problem Break a Palindrome • Errichto Algorithms • 39,252 views views
Watch 9 more video solutions →Practice Break a Palindrome with our built-in code editor and test cases.
Practice on FleetCode