VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-kth-character-of-decrypted-string/

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


  • Courses
  • Tutorials
  • Interview Prep

Find k'th character of decrypted string | Set 1

Last Updated : 23 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'.

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"

Input: "ab4c12ed3", k = 21
Output: e
Decrypted string is "ababababccccccccccccededed"

Approach: 

  1. The idea is simple, Initially take empty decrypted string. 
  2. decompress the string by reading substring and it's frequency one by one and append current substring in decrypted string by it's frequency. 
  3. Repeat the process till the end of string  
  4. print the Kth character from decrypted string. 

Algorithm:

  • Step 1: Initialize a string with the given encoded string and the value of k.
  • Step 2: Find the kth character in the encoded string.
  • Step 3: Check if last character of the string is alphabet or numeric value, if it's alphabet i.e. frequency is zero, append it to the string and return (k-1)th index.
  • Step 4: Print the output.

Implementation:


Output
e

Time Complexity: O(N) where N is length of string.
Auxiliary Space: O(N)
 

Exercise : The above solution builds the decoded string to find k'th character. Extend the solution to work in O(1) extra space.
Find k-th character of decrypted string | Set – 2

Comment
Article Tags: