Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements | 2D prefix sum for submatrix sum query for matrix ; Function to find the prefix sum of the matrix from i and j ; Function to count the number of ways to select equal sized subarrays such that they have atleast K common elements ; Combining the two arrays ; Calculating the 2D prefix sum ; Iterating through all the elements of matrix and considering them to be the bottom right ; Applying binary search over side length ; If sum of this submatrix >= k then new search space will be [ low , mid ] ; Else new search space will be [ mid + 1 , high ] ; Adding the total submatrices ; Driver Code
var prefix_2D = Array ( 2005 ) ; function subMatrixSum ( i , j , len ) { return prefix_2D [ i ] [ j ] - prefix_2D [ i ] [ j - len ] - prefix_2D [ i - len ] [ j ] + prefix_2D [ i - len ] [ j - len ] ; } function numberOfWays ( a , b , n , m , k ) { for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j <= m ; j ++ ) { if ( a [ i - 1 ] == b [ j - 1 ] ) prefix_2D [ i ] [ j ] = 1 ; else prefix_2D [ i ] [ j ] = 0 ; } } for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j <= m ; j ++ ) { prefix_2D [ i ] [ j ] += prefix_2D [ i ] [ j - 1 ] ; } } for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j <= m ; j ++ ) { prefix_2D [ i ] [ j ] += prefix_2D [ i - 1 ] [ j ] ; } } var answer = 0 ; for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j <= m ; j ++ ) { var low = 1 ; var high = Math . min ( i , j ) ; while ( low < high ) { var mid = ( low + high ) >> 1 ; if ( subMatrixSum ( i , j , mid ) >= k ) { high = mid ; } else { low = mid + 1 ; } } if ( subMatrixSum ( i , j , low ) >= k ) { answer += ( Math . min ( i , j ) - low + 1 ) ; } } } return answer ; } var N = 2 , M = 3 ; var A = [ 1 , 2 ] ; var B = [ 1 , 2 , 3 ] ; for ( i = 0 ; i < 205 ; i ++ ) prefix_2D [ i ] = Array ( 205 ) . fill ( 0 ) ; var K = 1 ; document . write ( numberOfWays ( A , B , N , M , K ) ) ;