Suppose we have two strings S and T, we have to check whether a string of the same length which is lexicographically bigger than S and smaller than T. We have to return -1 if no such string is available. We have to keep in mind that S = S1S2… Sn is termed to be lexicographically less than T = T1T2… Tn, provided there exists an i, so that S1= T1, S2= T2, … Si – 1= Ti – 1, Si < Ti.
So, if the input is like S = "bbb" and T = "ddd", then the output will be "bbc"
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def find_next(string): n = len(string) for i in range(n - 1, -1, -1): if string[i] != 'z': k = ord(string[i]) string[i] = chr(k + 1) return ''.join(string) string[i] = 'a' S = "bbb" T = "ddd" S = list(S) res = find_next(S) if res != T: print(res) else: print(-1)