VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-k-th-character-of-decrypted-string-set-2/

⇱ Find k-th character of decrypted string | Set - 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find k-th character of decrypted string | Set - 2

Last Updated : 11 Jul, 2025

Given an encoded string where repetitions of substrings are represented as substring followed by count of substrings. For example, if encrypted string is "ab2cd2" and k=4, so output will be 'b' because decrypted string is "ababcdcd" and 4th character is 'b'.
Note: Frequency of encrypted substring can be of more than one digit. For example, in "ab12c3", ab is repeated 12 times. No leading 0 is present in frequency of substring.

Examples: 

Input:  "a2b2c3", k = 5
Output:  c
Decrypted string is "aabbccc"

Input:  "ab4c2ed3", k = 9
Output :  c
Decrypted string is "ababababccededed"

The solution discussed in previous post requires additional O(n) space. The following post discuss a solution that requires constant space. The stepwise algorithm is: 

  1. Find length of current substring. Use two pointers. Fix one pointer at beginning of substring and move another pointer until a digit is not found.
  2. Find frequency of repetition by moving the second pointer further until an alphabet is not found.
  3. Find length of substring if it is repeated by multiplying frequency and its original length.
  4. If this length is less than k, then required character lies in substring that follows. Subtract this length from k to keep count of number of characters that are required to be covered.
  5. If length is less than or equal to k, then required character lies in current substring. As k is 1-indexed reduce it by 1 and then take its mod with original substring length. Required character is kth character from starting of substring which is pointed by first pointer.

Below is the implementation of the above approach: 


Output: 
e

 

Time Complexity: O(n) 
Auxiliary Space: O(1)
 

Comment