![]() |
VOOZH | about |
Given two strings s and t, the task is to remove all occurrences of t in s and return the modified string s, and you have to use the KMP algorithm to solve this.
Examples:
Input: s = "abcdefgabcabcabdefghabc", t = "abc"
Output: "defgdefgh"Input: s = "aaabbbccc", t = "bbb"
Output: "aaaccc"
Approach: To solve the problem follow the below idea:
We will use the KMP (Knuth-Morris-Pratt) algorithm to solve this problem. The KMP matching algorithm uses degenerating property (pattern having the same sub-patterns appearing more than once in the pattern) of the pattern and improves the worst-case complexity to O(n). The basic idea behind KMP’s algorithm is: whenever we detect a mismatch (after some matches), we already know some of the characters in the text of the next window. We take advantage of this information to avoid matching the characters that we know will anyway match.
First, we need to compute the LPS array for the pattern string t. The LPS array is an array of integers where lps[i] gives us the length of the longest proper prefix of t[0..i] which is also a suffix of t[0..i]. We can compute the LPS array using the following steps:
- Initialize len and i to 0, and lps[0] to 0.
- If t[i] and t[len] match, increment both len and i, and set lps[i] to len.
- If t[i] and t[len] do not match, we need to reset len to lps[len-1] if len is not equal to 0. If len is 0, we set lps[i] to 0 and increment i.
- Repeat the above two steps until we reach the end of t.
Once we have computed the LPS array, we can use it to find all occurrences of 't' in 's' and remove them. We can use two pointers, i and j, to traverse s and t, respectively, and a string ans to store the new string without t.
Below is the code to implement the above steps:
defgdefgh
Time Complexity: O(n + m), where n is the length of the string s and m is the length of the string t.
Auxiliary Space: O(m), as we use an array of size m to store the LPS array.