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’
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Reverse middle words of a string
- Lexicographically next string
- String formed with middle character of every right substring followed by left sequentially
- Lexicographically first palindromic string
- Lexicographically n-th permutation of a string
- Lexicographically largest sub-sequence of the given string
- Find n-th lexicographically permutation of a string | Set 2
- Lexicographically smallest string of length N and sum K
- Lexicographically smallest string after M operations
- Lexicographically largest string possible in one swap
- Lexicographically minimum string rotation | Set 1
- Lexicographically next greater string using same character set
- Lexicographically all Shortest Palindromic Substrings from a given string
- Find lexicographically smallest string in at most one swaps
- Replace every vowels with lexicographically next vowel in a String
- K-th lexicographically smallest unique substring of a given string
- Queries to answer the X-th smallest sub-string lexicographically