Thursday, September 23, 2021

[LeetCode] 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'.

Example:

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.
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.
Input: palindrome = "aa"
Output: "ab"
Input: palindrome = "aba"
Output: "abb"

Constraints:

  • 1 <= palindrome.length <= 1000
  • palindrome consists of only lowercase English letters.


Approach: Let's go greedy. We will make the first character 'a' which is not 'a' and in that way we will have a string which is not palindrome and also it will be the smallest string possible. Now what if the string have all 'a'. In that case we can change the last character to 'b'. The only problem with this approach will be if a string has all 'a's except the one character. For example "aba", here if we change the first non 'a' character the string will become "aaa".

To solve this problem we either traverse the whole string to see if now the string has all 'a's  or we can just check the non 'a' character in first half of the string as the string is palindrome, the last half will have the exact same characters. 

 

Implementation in C#:

    public string BreakPalindrome(string palindrome) 

    {

        if(palindrome.Length <= 1)

        {

            return "";

        }        

        char[] palindromeArr = palindrome.ToCharArray();

        for (int i = 0; i < palindromeArr.Length / 2; ++i)

        {

            if (palindromeArr[i] != 'a')

            {

                palindromeArr[i] = 'a';

                return new string(palindromeArr);

             }

        }

        palindromeArr[palindromeArr.Length - 1] = 'b';

        return new string(palindromeArr);

    }


Complexity: O(n)

No comments:

Post a Comment