Break a Palindrome - 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. 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'.

Input & Output

Example 1 — Replace First Non-'a'
$ Input: palindrome = "abccba"
Output: "aaccba"
💡 Note: The first non-'a' character is 'b' at position 1. Replace it with 'a' to get "aaccba", which is not a palindrome and lexicographically smallest.
Example 2 — All Characters Are 'a'
$ Input: palindrome = "aa"
Output: "ab"
💡 Note: All characters are 'a', so we change the last character to 'b' to get "ab", which breaks the palindrome.
Example 3 — Single Character
$ Input: palindrome = "a"
Output: ""
💡 Note: Cannot break a single character palindrome while maintaining the same length, so return empty string.

Constraints

  • 1 ≤ palindrome.length ≤ 1000
  • palindrome consists of only lowercase English letters
  • palindrome is a palindrome

Visualization

Tap to expand
Break a Palindrome INPUT Palindrome String: a 0 b 1 c 2 c 3 b 4 a 5 Mirror Property: Input Values: palindrome = "abccba" Length: 6 (even) First half: "abc" ALGORITHM STEPS 1 Check Length If len==1, return "" len=6 > 1, continue 2 Scan First Half Look for first non-'a' i=0: 'a' (skip) 3 Find Target i=1: 'b' != 'a' Found at index 1! 'b' --> 'a' 4 Replace Character Change s[1] to 'a' Breaks palindrome a b c ... FINAL RESULT Modified String: a a NEW c c b a NOT a Palindrome [OK] Lex Smallest [OK] Output: "aaccba" Greedy solution found! Key Insight: To get lexicographically smallest result, scan the FIRST HALF only and replace the first non-'a' character with 'a'. If all characters in first half are 'a', replace the LAST character with 'b'. TutorialsPoint - Break a Palindrome | Greedy - Replace First Non-'a' with 'a'
Asked in
Facebook 15 Amazon 12 Google 8 Microsoft 6
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen