Lexicographically shortest string of length at most K which is not a substring of given String | Function to return a set of all substrings of given string which have length less than or equal to k ; Function to print the lexicographically smallest substring of length atmost k which is not present in given string s ; All substrings of length atmost k present in string s are stored in this set ; Loop to change length of substring ; String with length = len which has all characters as ' a ' ; If the substrings set does not contain this string then we have found the answer ; Changing the likes of ' azz ' and ' daz ' to ' baa ' and ' dba ' respectively ; Reached a string like ' zz ' or ' zzz ' increase the length of the substring ; Given Input ; Function Call
function presentSubstring ( s , k ) { let st = new Set ( ) ; let n = s . length ; s = s . split ( " " ) ; for ( let i = 0 ; i < n ; i ++ ) { let s1 = " " ; for ( let j = 0 ; j < k && i + j < n ; j ++ ) { s1 += s [ i + j ] ; st . add ( s1 ) ; } } return st ; } function smallestSubstring ( s , k ) { let st = new Set ( ) ; st = presentSubstring ( s , k ) ; let index = 0 ; for ( let len = 1 ; len <= k ; len ++ ) { let t = new Array ( len ) . fill ( " " ) ; while ( true ) { if ( ! st . has ( t . join ( " " ) ) ) { return t . join ( " " ) ; } index = len - 1 ; while ( index >= 0 && t [ index ] == " " ) { t [ index ] = " " ; index -- ; } if ( index >= 0 ) t [ index ] = String . fromCharCode ( t [ index ] . charCodeAt ( 0 ) + 1 ) ; else break ; } } return " " ; } let s = " " ; let K = 3 ; document . write ( smallestSubstring ( s , K ) ) ;