VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-kth-character-sorted-concatenated-substrings-string/

⇱ Print Kth character in sorted concatenated substrings of a string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print Kth character in sorted concatenated substrings of a string

Last Updated : 13 Dec, 2023

Given a string of lower alphabetic characters, find K-th character in a string formed by substrings (of given string) when concatenated in sorted form. 

Examples:  

Input : str = “banana”
K = 10
Output : n
All substring in sorted form are,
"a", "an", "ana", "anan", "anana",
"b", "ba", "ban", "bana", "banan",
"banana", "n", "na", "nan", "nana"
Concatenated string = “aananaanana
nanabbabanbanabananbananannanannana”
We can see a 10th character in the
above concatenated string is ‘n’
which is our final answer.

A simple solution is to generate all substrings of a given string and store them in an array. Once substrings are generated, sort them and concatenate after sorting. Finally print K-th character in the concatenated string.

An efficient solution is based on counting distinct substring of a string using suffix array. Same method is used in solving this problem also. After getting suffix array and lcp array, we loop over all lcp values and for each such value, we calculate characters to skip. We keep subtracting these many characters from our K, when character to skip becomes more than K, we stop and loop over substrings corresponding to current lcp[i], in which we loop from lcp[i] till the maximum length of string and then print the Kth character. 

Implementation:


Output
n
Comment