VOOZH about

URL: https://www.geeksforgeeks.org/dsa/decrypt-message-from-given-code-by-replacing-all-with-prefix-values-of-encoded-string/

⇱ Decrypt message from given code by replacing all * with prefix values of encoded string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Decrypt message from given code by replacing all * with prefix values of encoded string

Last Updated : 23 Jul, 2025

Given a string str of length of N that is in the encoded form with alphabets and * . The task is to find the string from which it was generated. The required string can be generated from the encoded string by replacing all the * with the prefix values of the encoded string. 

Examples:

Input: str =  ab*c*d
Output: "ababcababcd"
Explanation: For the first occurrence of  "*", "ab" is the prefix. So '*' is replaced by "ab" resulting the string  to be "ababc*d"  and for the next '*' the prefix is "ababc". So the string will now change from "ababc*d" to "ababcababcd".

Input :  str = "z*z*z"
Output:  zzzzzzz

Approach: The solution is based on greedy approach. Follow the steps mentioned below to solve the problem:

  • Consider an empty string result.
  • Iterate over the given coded string.
    • if the current character in the string is not "*" then add the current character to the result.
    • Otherwise, if the current character is "*", add the result string formed till now with itself.
  • Return the result.

Below is the implementation of the given approach.


Output
ababcababcd

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment