Find a string in lexicographic order which is in between given two strings - GeeksforGeeks

09 Sep, 2021
Given two strings S and T, find a string of the same length which is lexicographically greater than S and smaller than T. Print “-1” if no such string is formed.(S > T) 
Note: string S = s1s2... sn is said to be lexicographically smaller than string T = t1t2... tn, if there exists an i, such that s1 = t1, s2 = t2, ... si – 1 = ti – 1, si < ti.
Examples: 
Input : S = "aaa", T = "ccc"
Output : aab
Explanation: 
Here, 'b' is greater than any 
letter in S[]('a') and smaller 
than any letter in T[]('c').

Input : S = "abcde", T = "abcdf"
Output : -1
Explanation: 
There is no other string between
S and T.              
Approach: Find a string which is lexicographically greater than string S and check if it is smaller than string T, if yes print the string next else print “-1”. To find string, iterate the string S in the reverse order, if the last letter is not ‘z’, increase the letter by one (to move to next letter). If it is ‘z’, change it to ‘a’ and move to the second last character. Compare the resultant string with string T, if both strings are equal print ‘-1’, else print the resultant string.
Below is the implementation of above approach:  
C++
Java
Python3
C#
Javascript
// CPP program to find the string// in lexicographic order which is// in between given two strings#include <bits/stdc++.h>using namespace std; // Function to find the lexicographically // next stringstring lexNext(string s, int n){      // Iterate from last character    for (int i = n - 1; i >= 0; i--)    {          // If not 'z', increase by one        if (s[i] != 'z')        {            s[i]++;            return s;        }                 // if 'z', change it to 'a'        s[i] = 'a';    }} // Driver Codeint main(){    string S = "abcdeg", T = "abcfgh";    int n = S.length();    string res = lexNext(S, n);     // If not equal, print the    // resultant string    if (res != T)        cout << res << endl;       else        cout << "-1" << endl;    return 0;}
//Java program to find the string// in lexicographic order which is// in between given two strings class GFG { // Function to find the lexicographically // next string    static String lexNext(String str, int n) {        char[] s = str.toCharArray();        // Iterate from last character        for (int i = n - 1; i >= 0; i--) {            // If not 'z', increase by one            if (s[i] != 'z') {                s[i]++;                return String.valueOf(s);            }             // if 'z', change it to 'a'            s[i] = 'a';        }        return null;    } // Driver Code    static public void main(String[] args) {        String S = "abcdeg", T = "abcfgh";        int n = S.length();        String res = lexNext(S, n);         // If not equal, print the        // resultant string        if (res != T) {            System.out.println(res);        } else {            System.out.println("-1");        }    }} // This code is contributed by 29AjayKumar
# Python3 program to find the string# in lexicographic order which is# in between given two strings # Function to find the lexicographically# next stringdef lexNext(s, n):     # Iterate from last character    for i in range(n - 1, -1, -1):         # If not 'z', increase by one        if s[i] != 'z':            k = ord(s[i])            s[i] = chr(k + 1)            return ''.join(s)         # if 'z', change it to 'a'        s[i] = 'a' # Driver Codeif __name__ == "__main__":    S = "abcdeg"    T = "abcfgh"    n = len(S)     S = list(S)    res = lexNext(S, n)     # If not equal, print the    # resultant string    if res != T:        print(res)    else:        print(-1) # This code is contributed by# sanjeev2552
//C# program to find the string// in lexicographic order which is// in between given two stringsusing System; public class GFG {  // Function to find the lexicographically // next string    static String lexNext(String str, int n) {        char[] s = str.ToCharArray();        // Iterate from last character        for (int i = n - 1; i >= 0; i--) {            // If not 'z', increase by one            if (s[i] != 'z') {                s[i]++;                return new String(s);            }              // if 'z', change it to 'a'            s[i] = 'a';        }        return null;    }  // Driver Code    static public void Main() {        String S = "abcdeg", T = "abcfgh";        int n = S.Length;        String res = lexNext(S, n);          // If not equal, print the        // resultant string        if (res != T) {            Console.Write(res);        } else {            Console.Write("-1");        }    }}  // This code is contributed by 29AjayKumar
<script> // JavaScript program to find the string// in lexicographic order which is// in between given two strings // Function to find the lexicographically // next stringfunction lexNext( s, n){      // Iterate from last character    for (let i = n - 1; i >= 0; i--)    {          // If not 'z', increase by one        if (s[i] != 'z')        {            let code = s.charCodeAt(i)+1;            let str = String.fromCharCode(code);            return s.substr(0,i)+str+s.substr(i+1);         }                 // if 'z', change it to 'a'        s[i] = 'a';    }     } // Driver Codelet S = "abcdeg";let T = "abcfgh";let n = S.length;let res = lexNext(S, n); // If not equal, print the// resultant stringif (res != T)   document.write( res,'<br>');     else     document.write("-1 <br>" );      </script>
Output:  
abcdeh
 
YouTubeGeeksforGeeks501K subscribersFind a string in lexicographic order which is in between two given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:00•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=XVDyj0eYQKU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
29AjayKumar
sanjeev2552
rohitsingh07052
simmytarika5
lexicographic-ordering
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Reverse words in a given string
Length of the longest substring without repeating characters
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews