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.
Input: S = “geeks2for2”, K = 15
Explanation: The new string S’ = “geeksgeeksforgeeksgeeksfor”. The 15th letter is “e”.
Input: S = “a2345”, K = 100
Explanation: The new string S’=”a” repeated 120 times. The 100th letter is “a”.
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:
Time Complexity: O(N), where N is the length of S.
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.