Queries to answer the X | C ++ 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 ; Driver code ; To store all the sub - strings ; Perform queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; void pre_process ( vector < string > & substrings , string s ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { string dup = " " ; for ( int j = i ; j < n ; j ++ ) { dup += s [ j ] ; substrings . push_back ( dup ) ; } } sort ( substrings . begin ( ) , substrings . end ( ) ) ; } int main ( ) { string s = " geek " ; vector < string > substrings ; pre_process ( substrings , s ) ; int queries [ ] = { 1 , 5 , 10 } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) cout << substrings [ queries [ i ] - 1 ] << endl ; return 0 ; }