Remove all occurrences of a word from a given string using Z-algorithm
Last Updated :
07 Nov, 2022
Given two strings str of length N and word of length M, the task is to remove all the occurrences of the string word from the string str.
Examples:
Input: str = "asmGeeksasmasmForasmGeeks", word = "asm"
Output: GeeksForGeeks
Explanation:
Removing "asm" from the string, str modifies str to GeeksForGeeks
Input: str = "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching", word = "km"
Output: Z-algorithmishelpfulinsearching
Explanation:
Removing "km" from the string, str modifies str to "Z-algorithmishelpfulinsearching".
Naive Approach: The simplest approach to solve this problem is to iterate over the characters of the string str. For every index, check if a substring can be found whose starting index is equal to the current index and the substring is equal to the string, word. If found to be true, then remove the substring. Finally, print the string.
Time Complexity: O(N2)
Auxiliary Space: O(1)
STL-based Approach: Remove all the occurrence of the string word from the string str using replace() method.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using Z-algorithm. Follow the steps below to solve the problem:
- Initialize a string, say res, to store the string by removing the words from the given string str.
- Initialize an array, say Z[], to store the Z-value of the string.
- Find all occurrences of the string word in the given string str using Z-algorithm.
- Finally, traverse the array Z[] and check if z[i + length(word) + 1] is equal to length(word) or not. If found to be true, then update i += length(word) - 1.
- Otherwise, append current character into the string res.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to fill the Z-array for str
void getZarr(string str, int Z[])
{
int n = str.length();
int k;
// L Stores start index of window
// which matches with prefix of str
int L = 0;
// R Stores end index of window
// which matches with prefix of str
int R = 0;
// Iterate over the characters of str
for (int i = 1; i < n; ++i) {
// If i is greater than R
if (i > R) {
// Update L and R
L = R = i;
// If substring match with prefix
while (R < n && str[R - L] == str[R]) {
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
else {
// Update k
k = i - L;
// if Z[k] is less than
// remaining interval
if (Z[k] < R - i + 1) {
// Update Z[i]
Z[i] = Z[k];
}
else {
// Start from R and check manually
L = i;
while (R < n && str[R - L] == str[R]) {
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
}
}
}
// Function to remove all the occurrences
// of word from str
string goodStr(string str, string word)
{
// Create concatenated string "P$T"
string concat = word + "$" + str;
int l = concat.length();
// Store Z array of concat
int Z[l];
getZarr(concat, Z);
// Stores string, str by removing all
// the occurrences of word from str
string res;
// Stores length of word
int pSize = word.size();
// Traverse the array, Z[]
for (int i = 0; i < l; ++i) {
// if Z[i + pSize + 1] equal to
// length of word
if (i + pSize < l - 1 && Z[i + pSize + 1] == pSize) {
// Update i
i += pSize - 1;
}
else if (i < str.length()) {
res += str[i];
}
}
return res;
}
// Driver Code
int main()
{
string str
= "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching";
string word = "km";
cout << goodStr(str, word);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to fill the Z-array for str
static void getZarr(String str, int Z[])
{
int n = str.length();
int k;
// L Stores start index of window
// which matches with prefix of str
int L = 0;
// R Stores end index of window
// which matches with prefix of str
int R = 0;
// Iterate over the characters of str
for (int i = 1; i < n; ++i)
{
// If i is greater than R
if (i > R)
{
// Update L and R
L = R = i;
// If subString match with prefix
while (R < n && str.charAt(R - L) ==
str.charAt(R))
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
else
{
// Update k
k = i - L;
// if Z[k] is less than
// remaining interval
if (Z[k] < R - i + 1)
{
// Update Z[i]
Z[i] = Z[k];
}
else
{
// Start from R and check manually
L = i;
while (R < n && str.charAt(R - L) ==
str.charAt(R))
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
}
}
}
// Function to remove all the occurrences
// of word from str
static String goodStr(String str, String word)
{
// Create concatenated String "P$T"
String concat = word + "$" + str;
int l = concat.length();
// Store Z array of concat
int []Z = new int[l];
getZarr(concat, Z);
// Stores String, str by removing all
// the occurrences of word from str
String res="";
// Stores length of word
int pSize = word.length();
// Traverse the array, Z[]
for (int i = 0; i < l; ++i) {
// if Z[i + pSize + 1] equal to
// length of word
if (i + pSize < l - 1 && Z[i + pSize + 1] == pSize) {
// Update i
i += pSize - 1;
}
else if (i < str.length()) {
res += str.charAt(i);
}
}
return res;
}
// Driver Code
public static void main(String[] args)
{
String str
= "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching";
String word = "km";
System.out.print(goodStr(str, word));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python 3 program for the above approach
# Function to fill the Z-array for str
def getZarr(st, Z):
n = len(st)
k = 0
# L Stores start index of window
# which matches with prefix of str
L = 0
# R Stores end index of window
# which matches with prefix of str
R = 0
# Iterate over the characters of str
for i in range(1, n):
# If i is greater than R
if (i > R):
# Update L and R
L = R = i
# If substring match with prefix
while (R < n and st[R - L] == st[R]):
# Update R
R += 1
# Update Z[i]
Z[i] = R - L
# Update R
R -= 1
else:
# Update k
k = i - L
# if Z[k] is less than
# remaining interval
if (Z[k] < R - i + 1):
# Update Z[i]
Z[i] = Z[k]
else:
# Start from R and check manually
L = i
while (R < n and st[R - L] == st[R]):
# Update R
R += 1
# Update Z[i]
Z[i] = R - L
# Update R
R -= 1
# Function to remove all the occurrences
# of word from str
def goodStr(st, word):
# Create concatenated string "P$T"
concat = word + "$" + st
l = len(concat)
# Store Z array of concat
Z = [0]*l
getZarr(concat, Z)
# Stores string, str by removing all
# the occurrences of word from str
res = ""
# Stores length of word
pSize = len(word)
# Traverse the array, Z[]
for i in range(l):
# if Z[i + pSize + 1] equal to
# length of word
if (i + pSize < l - 1 and Z[i + pSize + 1] == pSize):
# Update i
i += pSize - 1
elif (i < len(st)):
res += st[i]
return res
# Driver Code
if __name__ == "__main__":
st = "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching"
word = "km"
print(goodStr(st, word))
# This code is contributed by chitranayal.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
// Function to fill the Z-array for str
static void getZarr(string str, int[] Z)
{
int n = str.Length;
int k;
// L Stores start index of window
// which matches with prefix of str
int L = 0;
// R Stores end index of window
// which matches with prefix of str
int R = 0;
// Iterate over the characters of str
for (int i = 1; i < n; ++i)
{
// If i is greater than R
if (i > R)
{
// Update L and R
L = R = i;
// If subString match with prefix
while (R < n && str[R - L] ==
str[R])
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
else
{
// Update k
k = i - L;
// if Z[k] is less than
// remaining interval
if (Z[k] < R - i + 1)
{
// Update Z[i]
Z[i] = Z[k];
}
else
{
// Start from R and check manually
L = i;
while (R < n && str[R - L] ==
str[R])
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
}
}
}
// Function to remove all the occurrences
// of word from str
static string goodStr(string str, string word)
{
// Create concatenated String "P$T"
string concat = word + "$" + str;
int l = concat.Length;
// Store Z array of concat
int []Z = new int[l];
getZarr(concat, Z);
// Stores String, str by removing all
// the occurrences of word from str
string res="";
// Stores length of word
int pSize = word.Length;
// Traverse the array, Z[]
for (int i = 0; i < l; ++i) {
// if Z[i + pSize + 1] equal to
// length of word
if (i + pSize < l - 1 && Z[i + pSize + 1] == pSize) {
// Update i
i += pSize - 1;
}
else if (i < str.Length) {
res += str[i];
}
}
return res;
}
// Driver Code
static public void Main()
{
string str
= "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching";
string word = "km";
Console.WriteLine(goodStr(str, word));
}
}
// This code is contributed by sanjoy_62.
JavaScript
<script>
//js program for the above approach
// Function to fill the Z-array for str
function getZarr(str,Z)
{
let n = str.length;
let k;
// L Stores start index of window
// which matches with prefix of str
let L = 0;
// R Stores end index of window
// which matches with prefix of str
let R = 0;
// Iterate over the characters of str
for (let i = 1; i < n; ++i)
{
// If i is greater than R
if (i > R)
{
// Update L and R
L = R = i;
// If subString match with prefix
while (R < n && str[R - L] ==
str[R])
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
else
{
// Update k
k = i - L;
// if Z[k] is less than
// remaining interval
if (Z[k] < R - i + 1)
{
// Update Z[i]
Z[i] = Z[k];
}
else
{
// Start from R and check manually
L = i;
while (R < n && str[R - L] ==
str[R])
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
}
}
}
// Function to remove all the occurrences
// of word from str
function goodStr(str,word)
{
// Create concatenated String "P$T"
let concat = word + "$" + str;
let l = concat.length;
// Store Z array of concat
let Z = new Array(l);
getZarr(concat, Z);
// Stores String, str by removing all
// the occurrences of word from str
let res="";
// Stores length of word
let pSize = word.length;
// Traverse the array, Z[]
for (let i = 0; i < l; ++i) {
// if Z[i + pSize + 1] equal to
// length of word
if (i + pSize < l - 1 && Z[i + pSize + 1] == pSize) {
// Update i
i += pSize - 1;
}
else if (i < str.length) {
res += str[i];
}
}
return res;
}
// Driver Code
let str = "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching";
let word = "km";
document.write(goodStr(str, word));
</script>
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to fill the Z-array for str
void getZarr(string str, int Z[])
{
int n = str.length();
int k;
// L Stores start index of window
// which matches with prefix of str
int L = 0;
// R Stores end index of window
// which matches with prefix of str
int R = 0;
// Iterate over the characters of str
for (int i = 1; i < n; ++i) {
// If i is greater than R
if (i > R) {
// Update L and R
L = R = i;
// If substring match with prefix
while (R < n && str[R - L] == str[R]) {
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
else {
// Update k
k = i - L;
// if Z[k] is less than
// remaining interval
if (Z[k] < R - i + 1) {
// Update Z[i]
Z[i] = Z[k];
}
else {
// Start from R and check manually
L = i;
while (R < n && str[R - L] == str[R]) {
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
}
}
}
// Function to remove all the occurrences
// of word from str
string goodStr(string str, string word)
{
// Create concatenated string "P$T"
string concat = word + "$" + str;
int l = concat.length();
// Store Z array of concat
int Z[l];
getZarr(concat, Z);
// Stores string, str by removing all
// the occurrences of word from str
string res;
// Stores length of word
int pSize = word.size();
// Traverse the array, Z[]
for (int i = 0; i < l; ++i) {
// if Z[i + pSize + 1] equal to
// length of word
if (i + pSize < l - 1 && Z[i + pSize + 1] == pSize) {
// Update i
i += pSize - 1;
}
else if (i < str.length()) {
res += str[i];
}
}
return res;
}
// Driver Code
int main()
{
string str
= "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching";
string word = "km";
cout << goodStr(str, word);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to fill the Z-array for str
static void getZarr(String str, int Z[])
{
int n = str.length();
int k;
// L Stores start index of window
// which matches with prefix of str
int L = 0;
// R Stores end index of window
// which matches with prefix of str
int R = 0;
// Iterate over the characters of str
for (int i = 1; i < n; ++i)
{
// If i is greater than R
if (i > R)
{
// Update L and R
L = R = i;
// If subString match with prefix
while (R < n && str.charAt(R - L) ==
str.charAt(R))
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
else
{
// Update k
k = i - L;
// if Z[k] is less than
// remaining interval
if (Z[k] < R - i + 1)
{
// Update Z[i]
Z[i] = Z[k];
}
else
{
// Start from R and check manually
L = i;
while (R < n && str.charAt(R - L) ==
str.charAt(R))
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
}
}
}
// Function to remove all the occurrences
// of word from str
static String goodStr(String str, String word)
{
// Create concatenated String "P$T"
String concat = word + "$" + str;
int l = concat.length();
// Store Z array of concat
int []Z = new int[l];
getZarr(concat, Z);
// Stores String, str by removing all
// the occurrences of word from str
String res="";
// Stores length of word
int pSize = word.length();
// Traverse the array, Z[]
for (int i = 0; i < l; ++i) {
// if Z[i + pSize + 1] equal to
// length of word
if (i + pSize < l - 1 && Z[i + pSize + 1] == pSize) {
// Update i
i += pSize - 1;
}
else if (i < str.length()) {
res += str.charAt(i);
}
}
return res;
}
// Driver Code
public static void main(String[] args)
{
String str
= "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching";
String word = "km";
System.out.print(goodStr(str, word));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python 3 program for the above approach
# Function to fill the Z-array for str
def getZarr(st, Z):
n = len(st)
k = 0
# L Stores start index of window
# which matches with prefix of str
L = 0
# R Stores end index of window
# which matches with prefix of str
R = 0
# Iterate over the characters of str
for i in range(1, n):
# If i is greater than R
if (i > R):
# Update L and R
L = R = i
# If substring match with prefix
while (R < n and st[R - L] == st[R]):
# Update R
R += 1
# Update Z[i]
Z[i] = R - L
# Update R
R -= 1
else:
# Update k
k = i - L
# if Z[k] is less than
# remaining interval
if (Z[k] < R - i + 1):
# Update Z[i]
Z[i] = Z[k]
else:
# Start from R and check manually
L = i
while (R < n and st[R - L] == st[R]):
# Update R
R += 1
# Update Z[i]
Z[i] = R - L
# Update R
R -= 1
# Function to remove all the occurrences
# of word from str
def goodStr(st, word):
# Create concatenated string "P$T"
concat = word + "$" + st
l = len(concat)
# Store Z array of concat
Z = [0]*l
getZarr(concat, Z)
# Stores string, str by removing all
# the occurrences of word from str
res = ""
# Stores length of word
pSize = len(word)
# Traverse the array, Z[]
for i in range(l):
# if Z[i + pSize + 1] equal to
# length of word
if (i + pSize < l - 1 and Z[i + pSize + 1] == pSize):
# Update i
i += pSize - 1
elif (i < len(st)):
res += st[i]
return res
# Driver Code
if __name__ == "__main__":
st = "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching"
word = "km"
print(goodStr(st, word))
# This code is contributed by chitranayal.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
// Function to fill the Z-array for str
static void getZarr(string str, int[] Z)
{
int n = str.Length;
int k;
// L Stores start index of window
// which matches with prefix of str
int L = 0;
// R Stores end index of window
// which matches with prefix of str
int R = 0;
// Iterate over the characters of str
for (int i = 1; i < n; ++i)
{
// If i is greater than R
if (i > R)
{
// Update L and R
L = R = i;
// If subString match with prefix
while (R < n && str[R - L] ==
str[R])
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
else
{
// Update k
k = i - L;
// if Z[k] is less than
// remaining interval
if (Z[k] < R - i + 1)
{
// Update Z[i]
Z[i] = Z[k];
}
else
{
// Start from R and check manually
L = i;
while (R < n && str[R - L] ==
str[R])
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
}
}
}
// Function to remove all the occurrences
// of word from str
static string goodStr(string str, string word)
{
// Create concatenated String "P$T"
string concat = word + "$" + str;
int l = concat.Length;
// Store Z array of concat
int []Z = new int[l];
getZarr(concat, Z);
// Stores String, str by removing all
// the occurrences of word from str
string res="";
// Stores length of word
int pSize = word.Length;
// Traverse the array, Z[]
for (int i = 0; i < l; ++i) {
// if Z[i + pSize + 1] equal to
// length of word
if (i + pSize < l - 1 && Z[i + pSize + 1] == pSize) {
// Update i
i += pSize - 1;
}
else if (i < str.Length) {
res += str[i];
}
}
return res;
}
// Driver Code
static public void Main()
{
string str
= "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching";
string word = "km";
Console.WriteLine(goodStr(str, word));
}
}
// This code is contributed by sanjoy_62.
JavaScript
<script>
//js program for the above approach
// Function to fill the Z-array for str
function getZarr(str,Z)
{
let n = str.length;
let k;
// L Stores start index of window
// which matches with prefix of str
let L = 0;
// R Stores end index of window
// which matches with prefix of str
let R = 0;
// Iterate over the characters of str
for (let i = 1; i < n; ++i)
{
// If i is greater than R
if (i > R)
{
// Update L and R
L = R = i;
// If subString match with prefix
while (R < n && str[R - L] ==
str[R])
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
else
{
// Update k
k = i - L;
// if Z[k] is less than
// remaining interval
if (Z[k] < R - i + 1)
{
// Update Z[i]
Z[i] = Z[k];
}
else
{
// Start from R and check manually
L = i;
while (R < n && str[R - L] ==
str[R])
{
// Update R
R++;
}
// Update Z[i]
Z[i] = R - L;
// Update R
R--;
}
}
}
}
// Function to remove all the occurrences
// of word from str
function goodStr(str,word)
{
// Create concatenated String "P$T"
let concat = word + "$" + str;
let l = concat.length;
// Store Z array of concat
let Z = new Array(l);
getZarr(concat, Z);
// Stores String, str by removing all
// the occurrences of word from str
let res="";
// Stores length of word
let pSize = word.length;
// Traverse the array, Z[]
for (let i = 0; i < l; ++i) {
// if Z[i + pSize + 1] equal to
// length of word
if (i + pSize < l - 1 && Z[i + pSize + 1] == pSize) {
// Update i
i += pSize - 1;
}
else if (i < str.length) {
res += str[i];
}
}
return res;
}
// Driver Code
let str = "Z-kmalgorithmkmiskmkmkmhelpfulkminkmsearching";
let word = "km";
document.write(goodStr(str, word));
</script>
Time Complexity: O(N + M)
Auxiliary Space: O(N)
Similar Reads
Remove all occurrences of a string t in string s using Boyer-Moore Algorithm
Given a string s and string t, the task is to remove all occurrences of a string t in a string s using the Boyer-Moore algorithm. Examples: Input: s = "ababaababa", t = "aba" Output: baab Input: s = "Geeksforgeeks", t = "eek"Output: Gsforgs Approach: This can be solved with the following idea: We in
10 min read
Remove all occurrences of string t in string s using KMP Algorithm
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: T
8 min read
Remove last occurrence of a word from a given sentence string
Given two strings S and W of sizes N and M respectively, the task is to remove the last occurrence of W from S. If there is no occurrence of W in S, print S as it is. Examples: Input: S = âThis is GeeksForGeeksâ, W="Geeks"Output: This is GeeksForExplanation:The last occurrence of âGeeksâ in the stri
11 min read
Remove all occurrences of a character from a string using STL
Given a string S and a character C, the task is to remove all the occurrences of the character C from the given string. Examples: Input:vS = "GFG IS FUN", C = 'F' Output:GG IS UN Explanation: Removing all occurrences of the character 'F' modifies S to "GG IS UN". Therefore, the required output is GG
2 min read
Minimize length of a string by removing occurrences of another string from it as a substring
Given a string S and a string T, the task is to find the minimum possible length to which the string S can be reduced to after removing all possible occurrences of string T as a substring in string S. Examples: Input: S = "aabcbcbd", T = "abc"Output: 2Explanation:Removing the substring {S[1], ..., S
7 min read
Find starting index for every occurrence of given array B in array A using Z-Algorithm
Given two arrays A and B, the task is to find the starting index for every occurrence of array B in array A using Z-Algorithm.Examples: Input: A = {1, 2, 3, 2, 3}, B = {2, 3} Output: 1 3 Explanation: In array A, array B occurs at index 1 and index 3. Thus the answer is {1, 3}.Input: A = {1, 1, 1, 1,
10 min read
Count occurrences of a word in string
Given a two strings s and word. The task is to count the number of occurrences of the string word in the string s.Note: The string word should appear in s as a separate word, not as a substring within other words.Examples: Input: s = "GeeksforGeeks A computer science portal for geeks", word = "porta
11 min read
Maximize cost of removing all occurrences of substrings "ab" and "ba"
Given a string S and integers P and Q, which denotes the cost of removal of substrings "ab" and "ba" respectively from S, the task is to find the maximum cost of removing all occurrences of substrings "ab" and "ba". Examples: Input: S = "cbbaabbaab", P = 6, Q = 4Output: 22Explanation:Removing substr
10 min read
Remove the first and last character of each word in a string
Given the string the task is to remove the first and last character of each word in a string.Examples: Input: Geeks for geeksOutput: eek o eek Input: Geeksforgeeks is bestOutput: eeksforgeek es Approach : Split the String based on the spaceRun a loop from the first letter to the last letter.Check if
4 min read
Decode a given string by removing duplicate occurrences
Given encoded string str such that 'a' is written 1 time, 'b' is written 2 times, and so on, until 'z' is written 26 times, the task is to decode the given string str. Note: The letter may contain spaces and punctuation marks, so don't ignore those. Examples: Input: str = "bbadddd"Output: badExplana
6 min read