VOOZH about

URL: https://www.geeksforgeeks.org/dsa/queries-to-answer-the-x-th-smallest-sub-string-lexicographically/

⇱ Queries to answer the X-th smallest sub-string lexicographically - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Queries to answer the X-th smallest sub-string lexicographically

Last Updated : 11 Jul, 2025

Given a string str and Q queries. Every query consists of a number X, the task is to print the Xth lexicographically smallest sub-string of the given string str


Examples: 

Input: str = "geek", q[] = {1, 5, 10} 
Output: 

ek 

"e", "e", "ee", "eek", "ek", "g", "ge", "gee", "geek" and "k" are 
all the possible sub-strings in lexicographically sorted order.


Input: str = "abcgdhge", q[] = {15, 32} 
Output: 
bcgdhge 
gdhge 


Approach: Generate all the sub-strings and store them in any data structure and sort that data structure lexicographically. In the solution below, we have used a vector to store all the sub-strings and the inbuilt sort function sorts them in the given order. Now, for every query print vec[X - 1], which will be the Xth smallest sub-string. 


Below is the implementation of the above approach: 


Output: 
e
ek
k

 

Time Complexity: O(N2*logN), as we are using an inbuilt sort function to sort an array of size N*N. Where N is the length of the string.

Auxiliary Space: O(N2), as we are using extra space for storing the substrings.

Comment