Given two strings a and b. Our task is to print any string which is greater than a(lexicographically) but smaller than b(lexicographically). If it is impossible to get such string, print -1;
Input : a = "abg", b = "abj" Output : abh The string "abh" is lexicographically greater than "abg" and smaller than "abj" Input : a = "abc", b = "abd" Output :-1 There is no string which is lexicographically greater than a but smaller than b/
Since, there can be multiple strings which may satisfy the above condition, we convert string “a” into a string which is lexicographically next to “a”.
To find lexicographically next, we start traversing the string from backward and convert all the letter “z” to letter”a”. If we encounter any letter which is not “z”, then we increment it by one and further traversal will not be carried out.If this string is not smaller than “b”, then we will print -1 as no string can satisfy the above condition.
For example, string a=”ddzzz” and string b=”deaao”.So, starting from backward, we will convert all letter “z” to letter “a” until we reach to letter “d”(in this case).Increment “d” by one (to “e”) and break out from the loop.So, string a will become “deaaa” which is lexicographically greater than “ddzzz” and smaller than “deaao”.
Time Complexity: O(n) where n is length of string ‘a’
- 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
- Reverse middle words of a string
- Lexicographically next string
- Lexicographically first palindromic string
- Lexicographically n-th permutation of a string
- Lexicographically next greater string using same character set
- Find n-th lexicographically permutation of a string | Set 2
- Lexicographically largest sub-sequence of the given string
- Lexicographically smallest string of length N and sum K
- Lexicographically minimum string rotation | Set 1
- Queries to answer the X-th smallest sub-string lexicographically
- K-th lexicographically smallest unique substring of a given string
- Lexicographically smallest permutation of a string with given subsequences
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.