Next word that does not contain a palindrome and has characters from first k | Function to return lexicographically next word ; we made m as m + 97 that means our required string contains not more than m + 97 ( as per ASCII value ) in it . ; increment last alphabet to make next lexicographically next word . ; if i - th alphabet not in first k letters then make it as " a " and then increase ( i - 1 ) th letter ; to check whether formed string palindrome or not . ; increment i . ; if i less than or equals to one that means we not formed such word . ; Driver code
def findNextWord ( s , m ) : NEW_LINE INDENT m += 97 NEW_LINE n = len ( s ) NEW_LINE i = len ( s ) - 1 NEW_LINE s [ i ] = chr ( ord ( s [ i ] ) + 1 ) NEW_LINE while i >= 0 and i <= n - 1 : NEW_LINE INDENT if ord ( s [ i ] ) >= m : NEW_LINE INDENT s [ i ] = ' a ' NEW_LINE i -= 1 NEW_LINE s [ i ] = chr ( ord ( s [ i ] ) + 1 ) NEW_LINE DEDENT elif s [ i ] == s [ i - 1 ] or s [ i ] == s [ i - 2 ] : NEW_LINE INDENT s [ i ] = chr ( ord ( s [ i ] ) + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT if i <= - 1 : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' ' . join ( s ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abcd " NEW_LINE k = 4 NEW_LINE findNextWord ( list ( string ) , k ) NEW_LINE DEDENT