Magicsheet logo

Break a Palindrome

Medium
95.2%
Updated 6/1/2025

Break a Palindrome

What is this problem about?

You are given a palindromic string. You need to replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and is lexicographically the smallest possible. If it's impossible to break the palindrome (e.g., if the string has length 1), return an empty string.

Why is this asked in interviews?

Companies like Nvidia, Dell, and Oracle use this problem to test your understanding of lexicographical ordering and greedy strategies. It’s a great example of how a simple "greedy" choice can solve a seemingly complex problem. It tests your attention to edge cases, such as strings made entirely of 'a's or strings with an odd length.

Algorithmic pattern used

The Greedy pattern is the way to go. To make a string lexicographically smallest, you want to change the leftmost possible character to 'a'. However, you must ensure that this change doesn't result in another palindrome. Because the original string is already a palindrome, you only need to check the first half of the string. If you find a character that is not 'a', change it to 'a'. If all characters in the first half are 'a', then the "smallest" way to break the palindrome is to change the very last character to 'b'.

Example explanation

  1. Input: "abccba"
    • Check first half: 'a', 'b'.
    • 'a' is already the smallest. Move to 'b'.
    • Change 'b' to 'a'. Result: "aaccba". This is the smallest.
  2. Input: "aaaaa"
    • All characters in the first half are 'a'.
    • Change the last character to 'b'. Result: "aaaab".

Common mistakes candidates make

A common mistake is changing the middle character of an odd-length palindrome (e.g., changing 'b' in "aba" to "aaa"). This doesn't work because the string remains a palindrome! Another mistake is not returning an empty string for length-1 inputs. Finally, some candidates overcomplicate the check, forgetting that they only need to look at the first half of the string.

Interview preparation tip

Always think about the "smallest" possible change. In string problems, this almost always means looking at the leftmost characters first and trying to change them to 'a'.

Similar Questions