Lexicographically smallest and largest substring of size k | JavaScript program to find lexicographically largest and smallest substrings of size k . ; Initialize min and max as first substring of size k ; Consider all remaining substrings . We consider every substring ending with index i . ; Print result . ; Driver Code
function getSmallestAndLargest ( s , k ) { var currStr = s . substring ( 0 , k ) ; var lexMin = currStr ; var lexMax = currStr ; for ( var i = k ; i < s . length ; i ++ ) { currStr = currStr . substring ( 1 , k ) + s [ i ] ; if ( lexMax < currStr ) lexMax = currStr ; if ( lexMin > currStr ) lexMin = currStr ; } document . write ( lexMin + " " ) ; document . write ( lexMax + " " ) ; } var str = " " ; var k = 3 ; getSmallestAndLargest ( str , k ) ;