VOOZH about

URL: https://www.geeksforgeeks.org/dsa/encode-given-string-by-replacing-substrings-with-prefix-same-as-itself-with/

⇱ Encode given string by replacing substrings with prefix same as itself with * - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Encode given string by replacing substrings with prefix same as itself with *

Last Updated : 29 Dec, 2021

Given string str of size N containing only lowercase English letters. The task is to encrypt the string such that the substrings having same prefix as itself are replaced by a *. Generate the encrypted string.

Note: If the string can be encrypted in multiple ways, find the smallest encrypted string. 

Examples:

Input: str = "ababcababcd"
Output: ab*c*d
Explanation: The substring "ababc" starting from 5th index (0 based indexing) can be replaced by a '*'. So the string becomes "ababcababcd" ->  "ababc*d". Now the substring "ab" starting from 2nd index can again be replaced with a '*'. So the string becomes "ab*c*d"

Input: str = "zzzzzzz"
Output: z*z*z
Explanation: The string can be encrypted  in 2 ways: "z*z*z" and "z**zzz". Out of  the two "z*z*z" is smaller in length.

Approach: A simple solution to generate smallest encrypted string is to find the longest non-overlapping repeated substring and encrypt that substring first. To implement this use the following steps:

  • Create a stack to store the encrypted string.
  • Declare two pointers (i & j) to point to the 1st index and middle index respectively.
  • Now start traversing the string and repeat the loop until the entire string is scanned. Follow steps mentioned below for each iteration:
    • Compare both the substring from index i and j.
    • If both substrings are equal, then repeat the same process on this substring and store the remaining string into stack.
    • Else decrement the value of 2nd pointer ( j ) by 1.
  • Now pop all the elements from the stack and append a symbol "*" then store it in a output string.
  • Return the encrypted string.

Below is the implementation of the above approach.

 
 


Output
z*z*z


 

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


 

Comment