VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-forbidden-strings/

⇱ Remove the forbidden strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove the forbidden strings

Last Updated : 1 Mar, 2023

Given a string W, change the string in such a way that it does not contain any of the "forbidden" strings S1 to Sn as one of its substrings. The rules that govern this change are as follows:

  1. Case of the characters does not matter i.e "XyZ" is the same as "xYZ". 
  2. Change all the characters that are covered by the substrings in the original string W such that a particular letter lt occurs a maximum number of times in the changed string and the changed string is lexicographically the smallest string that can be obtained from all possible combinations. 
  3. Characters that are not within the forbidden substrings are not allowed to change. 
  4. The case of the changed character must be the same as the case of the original character at that position in string W
  5. If the letter lt is part of the substring then it must be changed to some other character according to the above rules.

Examples: 

Input : n = 3 
 s1 = "etr"
 s2 = "ed" 
 s3 = "ied"
 W = "PEtrUnited"
 letter = "d"
Output : PDddUnitda

Input : n = 1
 s1 = "PetrsDreamOh"
 W = "PetrsDreamOh"
 letter = h
Output : HhhhhHhhhhHa


Explanation: 

Example 1: First character P does not belong to any of the substrings therefore it is not changed. The next three characters form the substring "etr" and are changed to "Ddd". The next four characters do not belong to any of the forbidden substrings and remain unchanged. The next two characters form the substring "ed" and are changed to "da" since d is The last character itself, it is replaced with another character 'a' such that the string is lexicographically the smallest. 

Notice: "Etr" = "etr" and the changed substring "Ddd" has first character as 'D' since first letter of "Etr" is in uppercase.

Example 2: Since the entire string is a forbidden string, it is replaced with letter 'h' from first to second last character according to the case. The last character is 'h' therefore it is replaced with letter 'a' such that the string is lexicographically the smallest.

Approach: 

Check for every character of the string W, if it is the beginning of the any of the substrings or not. Use another array to keep record of the characters of W that are part of the forbidden strings and needs to be changed. 
The characters are changed according to the following rules: 

  1. If W[i] = letter and letter = 'a' then W[i] = 'b' 
  2. If W[i] = letter and letter !='a' then W[i] = 'a' 
  3. If W[i] != letter then W[i] = letter

The first and second condition will also be used when W[i] is an uppercase character. 

Below is the implementation of the above approach: 


Output
PDddUnitda

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

Comment
Article Tags:
Article Tags: