![]() |
VOOZH | about |
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:
Below is the implementation of the above approach.
z*z*z
Time Complexity: O(N. Log(N))
Auxiliary Space: O(N)