text: Find starting index for every occurrence of given array B in array A using Z | Function to calculate Z - Array ; Loop to calculate Z - Array ; Outside the Z - box ; Inside Z - box ; Helper function to merge two arrays and create a single array ; Array to store merged array ; Copying array B ; Adding a separator ; Copying array A ; Calling Z - function ; Function to help compute the Z array ; Printing indexes where array B occur ; Driver Code
code: function zArray ( arr ) { let n = arr . length ; let z = new Array ( n ) ; let r = 0 , l = 0 ; for ( let k = 1 ; k < n ; k ++ ) { if ( k > r ) { r = l = k ; while ( r < n && arr [ r ] == arr [ r - l ] ) r ++ ; z [ k ] = r - l ; r -- ; } else { let k1 = k - l ; if ( z [ k1 ] < r - k + 1 ) z [ k ] = z [ k1 ] ; else { l = k ; while ( r < n && arr [ r ] == arr [ r - l ] ) r ++ ; z [ k ] = r - l ; r -- ; } } } return z ; } function mergeArray ( A , B ) { let n = A . length ; let m = B . length ; let z = new Array ( ) ; let c = new Array ( n + m + 1 ) ; for ( let i = 0 ; i < m ; i ++ ) c [ i ] = B [ i ] ; c [ m ] = Number . MAX_SAFE_INTEGER ; for ( let i = 0 ; i < n ; i ++ ) c [ m + i + 1 ] = A [ i ] ; z = zArray ( c ) ; return z ; } function findZArray ( A , B , n ) { let flag = 0 ; let z = [ ] ; z = mergeArray ( A , B ) ; for ( let i = 0 ; i < z . length ; i ++ ) { if ( z [ i ] == n ) { document . write ( ( i - n - 1 ) + " " ) ; flag = 1 ; } } if ( flag == 0 ) { document . write ( " " ) ; } } let A = [ 1 , 2 , 3 , 2 , 3 , 2 ] ; let B = [ 2 , 3 ] ; let n = B . length ; findZArray ( A , B , n ) ;