K-th lexicographically smallest unique substring of a given string
Last Updated :
27 Apr, 2023
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: 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 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++
// 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
Java
// 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
Python3
# 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)
C#
// 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
JavaScript
<script>
// JavaScript implementation of the above approach
function kThLexString(st, k, n)
{
// Set to store the unique substring
var z = new Set();
for(var i = 0; i < n; i++)
{
// String to create each substring
var pp = "";
for(var j = i; j < i + k; j++)
{
if (j >= n)
break;
pp += st[j];
// Adding to set
z.add(pp);
}
}
var fin = [];
z.forEach(element => {
fin.push(element);
});
fin.sort();
// Printing kth substring
document.write( fin[k-1]);
}
// Driver code
var s = "geeksforgeeks";
var k = 5;
var n = s.length;
kThLexString(s, k, n);
</script>
Time Complexity: O(nk log(nk) where n is the length of the string, and k is the length of the substring.
Space Complexity: O(nk)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
12 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Linked List Data Structure A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read