Related Articles

# Get K-th letter of the decoded string formed by repeating substrings

• Difficulty Level : Medium
• Last Updated : 21 May, 2021

Given a string S containing letter and digit and an integer K where, and . The task is to return the K-th letter of the new string S’.
The new string S’ is formed from old string S by following steps:
1. If the character read is a letter, that letter is added at end of S’
2. If the character read is a digit, then entire string S’ repeatedly written d-1 more times in total.
Note: The new string is guaranteed to have less than 2^63 letters.
Examples:

Input: S = “geeks2for2”, K = 15
Output: “e”
Explanation: The new string S’ = “geeksgeeksforgeeksgeeksfor”. The 15th letter is “e”.
Input: S = “a2345”, K = 100
Output: “a”
Explanation: The new string S’=”a” repeated 120 times. The 100th letter is “a”.

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Let us take a new string like S’ = “geeksgeeksgeeksgeeksgeeks” and an index K = 22, then the answer at K = 22 is the same if K = 2
In general, when a string is equal to some word with size length repeated some number of times (such as geeks with size = 5 repeated 5 times), then the answer will be same for the index K as it is for the index K % size.
Using this insight and working backwards, we keep track of the size of the new string S’. Whenever the string S’ would equal some word repeated d times, we can reduce K to K % (lengthof(word)).
We first find the length of the new string S’. After, this we’ll work backwards, keeping track of size: the length of the new string after parsing symbols S, S, …, S[i].
If we see a digit S[i], it means the size of the new string after parsing S, S, …, S[i-1] will be (size / toInteger(S[i])). Otherwise, it will be size – 1.
Below is the implementation of above approach:

## C++

 // CPP implementation of above approach#include using namespace std; // Function to return the K-th letter from new String.string K_thletter(string S, int K){     int N = S.size();    long size = 0;     // finding size = length of new string S'    for (int i = 0; i < N; ++i) {        if (isdigit(S[i]))            size = size * (S[i] - '0');        else            size += 1;    }     // get the K-th letter    for (int i = N - 1; i >= 0; --i) {        K %= size;         if (K == 0 && isalpha(S[i]))            return (string) "" + S[i];         if (isdigit(S[i]))            size = size / (S[i] - '0');        else            size -= 1;    }} // Driver programint main(){    string S = "geeks2for2";    int K = 15;     cout << K_thletter(S, K);     return 0;} // This code is written by Sanjit_Prasad

## Java

 // Java implementation of above approachclass GFG{    // Function to return the K-th letter from new String.    static String K_thletter(String S, int K)    {        int N = S.length();        long size = 0;         // finding size = length of new string S'        for (int i = 0; i < N; ++i)        {            if (Character.isDigit(S.charAt(i)))            {                size = size * (S.charAt(i) - '0');            }            else            {                size += 1;            }        }         // get the K-th letter        for (int i = N - 1; i >= 0; --i)        {            K %= size;            if (K == 0 && Character.isAlphabetic(S.charAt(i)))            {                return (String) "" + S.charAt(i);            }             if (Character.isDigit(S.charAt(i)))            {                size = size / (S.charAt(i) - '0');            }            else            {                size -= 1;            }        }        return null;    }     // Driver program    public static void main(String[] args)    {        String S = "geeks2for2";        int K = 15;        System.out.println(K_thletter(S, K));    }} // This code is contributed by Rajput-Ji

## Python3

 # Python3 implementation of above approach # Function to return the K-th letter# from new String.def K_thletter(S, K):     N = len(S)    size = 0     # finding size = length of new string S'    for i in range(0, N):        if S[i].isdigit():            size = size * int(S[i])        else:            size += 1     # get the K-th letter    for i in range(N - 1, -1, -1):        K %= size         if K == 0 and S[i].isalpha():            return S[i]         if S[i].isdigit():            size = size // int(S[i])        else:            size -= 1 # Driver Codeif __name__ == "__main__":     S = "geeks2for2"    K = 15     print(K_thletter(S, K)) # This code is contributed# by Rituraj Jain

## C#

 // C# implementation of the above approachusing System;         class GFG{    // Function to return the K-th letter from new String.    static String K_thletter(String S, int K)    {        int N = S.Length;        long size = 0;         // finding size = length of new string S'        for (int i = 0; i < N; ++i)        {            if (char.IsDigit(S[i]))            {                size = size * (S[i] - '0');            }            else            {                size += 1;            }        }         // get the K-th letter        for (int i = N - 1; i >= 0; --i)        {            K %= (int)size;            if (K == 0 && char.IsLetter(S[i]))            {                return (String) "" + S[i];            }             if (char.IsDigit(S[i]))            {                size = size / (S[i] - '0');            }            else            {                size -= 1;            }        }        return null;    }     // Driver code    public static void Main(String[] args)    {        String S = "geeks2for2";        int K = 15;        Console.WriteLine(K_thletter(S, K));    }} // This code has been contributed by 29AjayKumar

## Javascript

 

Output:

e

Time Complexity: O(N), where N is the length of S.

My Personal Notes arrow_drop_up