Lexicographically smallest and largest substring of size k | CPP 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getSmallestAndLargest ( string s , int k ) { string currStr = s . substr ( 0 , k ) ; string lexMin = currStr ; string lexMax = currStr ; for ( int i = k ; i < s . length ( ) ; i ++ ) { currStr = currStr . substr ( 1 , k ) + s [ i ] ; if ( lexMax < currStr ) lexMax = currStr ; if ( lexMin > currStr ) lexMin = currStr ; } cout << ( lexMin ) << endl ; cout << ( lexMax ) << endl ; } int main ( ) { string str = " GeeksForGeeks " ; int k = 3 ; getSmallestAndLargest ( str , k ) ; }