Given a string, find lexicographically next string.
Input : geeks Output : geekt The last character 's' is changed to 't'. Input : raavz Output : raawz Since we can't increase last character, we increment previous character. Input : zzz Output : zzza
If string is empty, we return ‘a’. If string contains all characters as ‘z’, we append ‘a’ at the end. Otherwise we find first character from end which is not z and increment it.
# Python 3 program to find lexicographically
# next string
# If string is empty.
if (s == ” “):
# Find first character from right
# which is not z.
i = len(s) – 1
while (s[i] == ‘z’ and i >= 0):
i -= 1
# If all characters are ‘z’, append
# an ‘a’ at the end.
if (i == -1):
s = s + ‘a’
# If there are some non-z characters
s = s.replace(s[i], chr(ord(s[i]) + 1), 1)
# Driver code
if __name__ == ‘__main__’:
str = “samez”
# This code is contributed by
This article is contributed by Pawan Asipu. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Lexicographically first palindromic string
- Lexicographically n-th permutation of a string
- Lexicographically middle string
- Lexicographically largest sub-sequence of the given string
- Lexicographically minimum string rotation | Set 1
- Find n-th lexicographically permutation of a string | Set 2
- Lexicographically next greater string using same character set
- K-th lexicographically smallest unique substring of a given string
- Queries to answer the X-th smallest sub-string lexicographically
- Lexicographically first alternate vowel and consonant string
- Lexicographically smallest permutation of a string with given subsequences
- Lexicographically largest string formed from the characters in range L and R