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

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 −

  • n := size of string
  • for i in range n - 1 to 0, decrease by 1, do
    • if string[i] is not same as 'z', then
      • k := ASCII of (string[i])
      • string[i] := character from ASCII (k + 1)
      • join string characters and return
    • string[i] := 'a'


Let us see the following implementation to get better understanding −

 Live Demo

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:


"bbb", "ddd"