K-th lexicographically smallest unique substring of a given string

Given a string S. The task is to print the K-th lexicographically the 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.

Examples:

Input: str = “aba”, k = 4 
Output:
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 suffixes 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: 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the above approach
#include<bits/stdc++.h>
using namespace std;
 
void kThLexString(string st, int k, int n)
{
     
    // Set to store the unique substring
    set<string> z;
     
    for(int i = 0; i < n; i++)
    {
         
       // String to create each substring
       string pp;
        
       for(int j = i; j < i + k; j++)
       {
          if (j >= n)
              break;
          pp += st[j];
           
          // Adding to set
          z.insert(pp);
       }
    }
     
    // Converting set into a list
    vector<string> fin(z.begin(), z.end());
     
    // Sorting the strings int the list
    // into lexicographical order
    sort(fin.begin(), fin.end());
 
    // Printing kth substring
    cout << fin[k - 1];
}
 
// Driver code
int main()
{
    string s = "geeksforgeeks";
    int k = 5;
    int n = s.length();
     
    kThLexString(s, k, n);
}
 
// This code is contributed by yatinagg

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of
// the above approach
import java.util.*;
class GFG{
     
public static void kThLexString(String st,
                                int k, int n)
{
    // Set to store the unique substring
    Set<String> z = new HashSet<String>();
     
    for(int i = 0; i < n; i++)
    {
        // String to create each substring
        String pp = "";
     
        for(int j = i; j < i + k; j++)
        {
        if (j >= n)
            break;
        pp += st.charAt(j);
     
        // Adding to set
        z.add(pp);
        }
    }
     
    // Converting set into a list
    Vector<String> fin = new Vector<String>();
    fin.addAll(z);
     
    // Sorting the strings int the list
    // into lexicographical order
    Collections.sort(fin);
     
    // Printing kth substring
    System.out.print(fin.get(k - 1));
}
 
// Driver Code
public static void main(String[] args)
{
    String s = "geeksforgeeks";
    int k = 5;
    int n = s.length();
    kThLexString(s, k, n);
}
}
 
// This code is contributed by divyeshrabadiya07

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 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):
 
                break
 
            pp += s[j]
            # adding to set
            z.add(pp)
 
    # converting set into a list
    fin = list(z)
     
    # sorting the strings int the list
    # into lexicographical order
    fin.sort()
 
    # printing kth substring
    print(fin[k - 1])
 
 
s = "geeksforgeeks"
 
k = 5
 
n = len(s)
kThLexString(s, k, n)

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of
// the above approach
using System;
using System.Collections.Generic;
using System.Collections;
 
class GFG{
      
public static void kThLexString(string st,
                                int k, int n)
{
     
    // Set to store the unique substring
    HashSet<string> z = new HashSet<string>();
      
    for(int i = 0; i < n; i++)
    {
         
        // String to create each substring
        string pp = "";
      
        for(int j = i; j < i + k; j++)
        {
            if (j >= n)
                break;
                 
            pp += st[j];
          
            // Adding to set
            z.Add(pp);
        }
    }
     
    // Converting set into a list
    ArrayList fin = new ArrayList();
     
    foreach(string s in z)
    {
        fin.Add(s);
    }
     
    // Sorting the strings int the list
    // into lexicographical order
    fin.Sort();
      
    // Printing kth substring
    Console.Write(fin[k - 1]);
}
  
// Driver Code
public static void Main(string[] args)
{
    string s = "geeksforgeeks";
    int k = 5;
    int n = s.Length;
     
    kThLexString(s, k, n);
}
}
 
// This code is contributed by rutvik_56

chevron_right


Output: 

eeksf


 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


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.