Break a Palindrome

medium string greedy

Problem

Given a palindromic lowercase string palindrome, replace exactly one character so the result is the lexicographically smallest non-palindrome. Return the new string, or "" if impossible (length 1).

Inputpalindrome = "abccba"
Output"aaccba"
The first 'b' in the left half is swapped to 'a'.

def break_palindrome(p):
    n = len(p)
    if n < 2: return ""
    s = list(p)
    for i in range(n // 2):
        if s[i] != 'a':
            s[i] = 'a'
            return "".join(s)
    s[-1] = 'b'
    return "".join(s)
function breakPalindrome(p) {
  const n = p.length;
  if (n < 2) return "";
  const s = p.split("");
  for (let i = 0; i < Math.floor(n / 2); i++) {
    if (s[i] !== 'a') { s[i] = 'a'; return s.join(""); }
  }
  s[n - 1] = 'b';
  return s.join("");
}
class Solution {
    public String breakPalindrome(String p) {
        int n = p.length();
        if (n < 2) return "";
        char[] s = p.toCharArray();
        for (int i = 0; i < n / 2; i++) {
            if (s[i] != 'a') { s[i] = 'a'; return new String(s); }
        }
        s[n - 1] = 'b';
        return new String(s);
    }
}
string breakPalindrome(string p) {
    int n = p.size();
    if (n < 2) return "";
    for (int i = 0; i < n / 2; i++) {
        if (p[i] != 'a') { p[i] = 'a'; return p; }
    }
    p[n - 1] = 'b';
    return p;
}
Time: O(n) Space: O(n)