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 for above function .
function findNextWord ( s , m ) { m += 97 ; var n = s . length ; var i = s . length - 1 ; s [ i ] = String . fromCharCode ( s [ i ] . charCodeAt ( 0 ) + 1 ) ; while ( i >= 0 && i <= n - 1 ) { if ( s [ i ] . charCodeAt ( 0 ) >= m ) { s [ i ] = ' ' ; s [ i - 1 ] = String . fromCharCode ( s [ i - 1 ] . charCodeAt ( 0 ) + 1 ) ; i -- ; } else if ( s [ i ] == s [ i - 1 ] s [ i ] == s [ i - 2 ] ) s [ i ] = String . fromCharCode ( s [ i ] . charCodeAt ( 0 ) + 1 ) ; else i ++ ; } if ( i <= - 1 ) document . write ( " " ) ; else document . write ( s . join ( ' ' ) ) ; } var str = " " . split ( ' ' ) ; var k = 4 ; findNextWord ( str , k ) ;