Remove all occurrences of a word from a given string using Z | Function to fill the Z - array for str ; L Stores start index of window which matches with prefix of str ; R Stores end index of window which matches with prefix of str ; Iterate over the characters of str ; If i is greater thn R ; Update L and R ; If subString match with prefix ; Update R ; Update Z [ i ] ; Update R ; Update k ; if Z [ k ] is less than remaining interval ; Update Z [ i ] ; Start from R and check manually ; Update R ; Update Z [ i ] ; Update R ; Function to remove all the occurrences of word from str ; Create concatenated String " P $ T " ; Store Z array of concat ; Stores String , str by removing all the occurrences of word from str ; Stores length of word ; Traverse the array , Z [ ] ; if Z [ i + pSize + 1 ] equal to length of word ; Update i ; Driver Code
function getZarr ( str , Z ) { let n = str . length ; let k ; let L = 0 ; let R = 0 ; for ( let i = 1 ; i < n ; ++ i ) { if ( i > R ) { L = R = i ; while ( R < n && str [ R - L ] == str [ R ] ) { R ++ ; } Z [ i ] = R - L ; R -- ; } else { k = i - L ; if ( Z [ k ] < R - i + 1 ) { Z [ i ] = Z [ k ] ; } else { L = i ; while ( R < n && str [ R - L ] == str [ R ] ) { R ++ ; } Z [ i ] = R - L ; R -- ; } } } } function goodStr ( str , word ) { let concat = word + " " + str ; let l = concat . length ; let Z = new Array ( l ) ; getZarr ( concat , Z ) ; let res = " " ; let pSize = word . length ; for ( let i = 0 ; i < l ; ++ i ) { if ( i + pSize < l - 1 && Z [ i + pSize + 1 ] == pSize ) { i += pSize - 1 ; } else if ( i < str . length ) { res += str [ i ] ; } } return res ; } let str = " " ; let word = " " ; document . write ( goodStr ( str , word ) ) ;