
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- if s[i] is not same as "a", then
- 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
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
Advertisements