Program to find lexicographically smallest non-palindromic string in Python


Suppose we have a string s that is a palindrome. We have to change one character such that s is no longer a palindrome and it is lexicographically smallest.

So, if the input is like s = "level", then the output will be "aevel", as we can change the first "l" to "a" to get the lexicographically smallest string that is not palindrome.

To solve this, we will follow these steps −

  • for i in range 0 to integer part of(size of s / 2), do
    • if s[i] is not same as "a", then
      • s := a new list from all characters in s
      • s[i] := "a"
      • join all characters in s and return
  • s := a new list from all characters in s
  • last element of s := "b"
  • join all characters in s and return

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      for i in range(len(s) // 2):
         if s[i] != "a":
            s = list(s)
            s[i] = "a"
            return "".join(s)
      s = list(s)
      s[-1] = "b"
      return "".join(s)
ob = Solution()
s = "level"
print(ob.solve(s))

Input

"level"

Output

aevel

Updated on: 19-Nov-2020

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements