K-th lexicographically smallest unique substring of a given string

Given a string S. The task is to print the K-th lexicographically smallest one among the different substrings of s.

A substring of s is a string obtained by taking out a non-empty contiguous part in s.
For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z and an empty string are not. Also, we say that substrings are different when they are different as strings.


Input: str = “aba”, k = 4
Output: b
All unique substrings are a, ab, aba, b, ba.
Thus the 4th lexicographically smallest substring is b.

Input: str = “geeksforgeeks”, k = 5
Output: eeksf

Approach: For an arbitrary string t, each of its proper suffix is lexicographically smaller than t, and the lexicographic
rank of t is at least |t|. Thus, the length of the answer is at most K.
Generate all substrings of s whose lengths are at most K. Sort them, unique them, and print the K-th one, where N = |S|.

Below is the implementation of the above approach:





# Python implementation of the above approach
def kThLexString(st, k, n):
    # Set to store the unique substring
    z = set() 
    for i in range(n):
        # String to create each substring
        pp = "" 
        for j in range(i, i + k):
            if (j >= n):
            pp += s[j]
            # adding to set
    # converting set into a list
    fin = list(z) 
    # sorting the strings int the list
    # into lexicographical order
    # printing kth substring
    print(fin[k - 1]) 
s = "geeksforgeeks"
k = 5
n = len(s)
kThLexString(s, k, n)




GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.