Queries to answer the X | Java implementation of the approach ; Function to pre - process the sub - strings in sorted order ; Generate all substrings ; Iterate to find all sub - strings ; Store the sub - string in the vector ; Sort the substrings lexicographically ; sort ( substrings . begin ( ) , substrings . end ( ) ) ; ; Driver code ; To store all the sub - strings ; Perform queries
import java . util . * ; class GFG { static void pre_process ( String substrings [ ] , String s ) { int n = s . length ( ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { String dup = " " ; for ( int j = i ; j < n ; j ++ ) { dup += s . charAt ( j ) ; substrings [ count ++ ] = dup ; } } int size = substrings . length ; for ( int i = 0 ; i < size - 1 ; i ++ ) { for ( int j = i + 1 ; j < substrings . length ; j ++ ) { if ( substrings [ i ] . compareTo ( substrings [ j ] ) > 0 ) { String temp = substrings [ i ] ; substrings [ i ] = substrings [ j ] ; substrings [ j ] = temp ; } } } } public static void main ( String args [ ] ) { String s = " geek " ; String substrings [ ] = new String [ 10 ] ; pre_process ( substrings , s ) ; int queries [ ] = { 1 , 5 , 10 } ; int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) System . out . println ( substrings [ queries [ i ] - 1 ] ) ; } }