-1

Given a palindromic string palindrome, replace exactly one character by any lowercase English letter so that the string becomes the lexicographically smallest possible string that isn't a palindrome.

After doing so, return the final string. If there is no way to do so, return the empty string.

I have come up with the following, which takes O(n) time and O(1) space:

def breakPalindrome(self, S):
    for i in xrange(len(S) / 2):
        if S[i] != 'a':
            return S[:i] + 'a' + S[i + 1:]
    return S[:-1] + 'b' if S[:-1] else ''

Is there a better solution? Please correct me if there's some mistake in time or space complexity.

curiousD
  • 27
  • 6

1 Answers1

0
  • Bug in your code: Odd palindromes. Input 'aba' gives output 'abb'. The correct output should be 'aaa'
  • Return "" on len(palindrome) == 1 is not a right thing to do. I would treat empty string as a palindrome.
  • Strings are immutable in python. So, space complexity of your solution is O(n). It can't be any better.
  • There can't be a better solution in terms of space or time complexity. You have to check the whole string in the worst case e.g. string contains only 'a's.
  • In languages where strings are mutable e.g. C++, the space complexity could be O(1) as one can change a character at an index in constant time like palindrome[i] = 'a' or palindrome[palindrome.size() - 1] = 'b'.
Shridhar R Kulkarni
  • 6,653
  • 3
  • 37
  • 57