Given a string and a pattern, in-place replace all non-overlapping occurrences of the pattern in the string by a specified character.

1st Variant: Replace each occurrence of the pattern

Input:
 
String = “ABCABCXABC”;
Pattern = “ABC”;
Character = ‘@’;
 
Output: @@X@

The idea is to compare the substring formed by S[i,i+n] with the given pattern P for each position i in string S. If P matches with the substring S[i,i+n], replace the substring with the specified character; otherwise, copy the current character to the next free position from the beginning of the array.

Following is the implementation in C, Java, and Python based on the above idea:

C


Download  Run Code

Output:

@@X@

Java


Download  Run Code

Output:

@@X@

Python


Download  Run Code

Output:

@@X@

2nd Variant: Replace single or multiple occurrences of the pattern

String = “ABCABCXABC”;
Pattern = “ABC”;
Character = ‘@’;
 
Output: @X@

Here, if substring S[i,i+n] matches the given pattern P, immediately check for the substring formed by the next set of n characters. The idea is to replace all such multiple consecutive occurrences of the pattern with the specified character.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

@X@

Java


Download  Run Code

Output:

@X@

Python


Download  Run Code

Output:

@X@

The best-case time complexity of the above solution is O(n + m), and the worst-case time complexity of the above solution is O(n.m), where n is the length of the text and m is the length of the pattern. The best case happens when the string is entirely made up of consecutive occurrences of the pattern.