LeetCode 1328: Break a Palindrome Solution

Master LeetCode problem 1328 (Break a Palindrome), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1328. Break a Palindrome

Problem Explanation

Explanation:

To solve this problem, we can iterate through half of the given palindrome string and try to make it non-palindromic by changing characters in the first half. We need to find the first non-'a' character and replace it with 'a'. If there are no non-'a' characters, we can replace the last character with 'b'.

  • If the length of the palindrome string is 1, we return an empty string as it is not possible to make a single character non-palindromic.
  • Otherwise, we iterate through the first half of the string until we find a non-'a' character. If no such character is found, we replace the last character with 'b'.

Solution Code

class Solution {
    public String breakPalindrome(String palindrome) {
        if (palindrome.length() == 1) {
            return "";
        }
        
        char[] chars = palindrome.toCharArray();
        
        for (int i = 0; i < chars.length / 2; i++) {
            if (chars[i] != 'a') {
                chars[i] = 'a';
                return String.valueOf(chars);
            }
        }
        
        chars[chars.length - 1] = 'b';
        return String.valueOf(chars);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1328 (Break a Palindrome)?

This page provides optimized solutions for LeetCode problem 1328 (Break a Palindrome) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1328 (Break a Palindrome)?

The time complexity for LeetCode 1328 (Break a Palindrome) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1328 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1328 in Java, C++, or Python.

Back to LeetCode Solutions