Lexicographically smallest and largest substring of size k | C # program to find lexicographically largest and smallest substrings of size k . ; Utility compare ; 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
using System ; class GFG { static int CompareTo ( String s1 , String s2 ) { for ( int i = 0 ; i < s1 . Length < s2 . Length ; i ++ ) { if ( s1 [ i ] < s2 [ i ] ) return - 1 ; else if ( s1 [ i ] > s2 [ i ] ) return 1 ; } return 0 ; } static void getSmallestAndLargest ( String s , int k ) { String currStr = s . Substring ( 0 , k ) ; String lexMin = currStr ; String lexMax = currStr ; for ( int i = k ; i < s . Length ; i ++ ) { currStr = currStr . Substring ( 1 , k - 1 ) + " " + s [ i ] ; if ( CompareTo ( lexMax , currStr ) < 0 ) lexMax = currStr ; if ( CompareTo ( lexMin , currStr ) > 0 ) lexMin = currStr ; } Console . WriteLine ( lexMin ) ; Console . WriteLine ( lexMax ) ; } public static void Main ( String [ ] args ) { String str = " GeeksForGeeks " ; int k = 3 ; getSmallestAndLargest ( str , k ) ; } }