Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements | C # implementation to count the number of ways to select equal sized subarrays such that they have atleast K common 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
using System ; class GFG { static int [ , ] prefix_2D = new int [ 2005 , 2005 ] ; static int subMatrixSum ( int i , int j , int len ) { return prefix_2D [ i , j ] - prefix_2D [ i , j - len ] - prefix_2D [ i - len , j ] + prefix_2D [ i - len , j - len ] ; } static int numberOfWays ( int [ ] a , int [ ] b , int n , int m , int k ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { if ( a [ i - 1 ] == b [ j - 1 ] ) prefix_2D [ i , j ] = 1 ; else prefix_2D [ i , j ] = 0 ; } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { prefix_2D [ i , j ] += prefix_2D [ i , j - 1 ] ; } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { prefix_2D [ i , j ] += prefix_2D [ i - 1 , j ] ; } } int answer = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { int low = 1 ; int high = Math . Min ( i , j ) ; while ( low < high ) { int 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 ; } public static void Main ( String [ ] args ) { int N = 2 , M = 3 ; int [ ] A = { 1 , 2 } ; int [ ] B = { 1 , 2 , 3 } ; int K = 1 ; Console . Write ( numberOfWays ( A , B , N , M , K ) ) ; } }