Count of subarrays having exactly K perfect square numbers | A utility function to check if the number n is perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; Function to find number of subarrays with sum exactly equal to k ; Map to store number of subarrays starting from index zero having particular value of sum . ; To store the sum of element traverse so far ; Add current element to currsum ; If currsum = K , then a new subarray is found ; If currsum > K then find the no . of subarrays with sum currsum - K and exclude those subarrays ; Add currsum to count of different values of sum ; Return the final result ; Function to count the subarray with K perfect square numbers ; Update the array element ; If current element is perfect square then update the arr [ i ] to 1 ; Else change arr [ i ] to 0 ; Function Call ; Driver code ; Function Call
function isPerfectSquare ( x ) { let sr = Math . sqrt ( x ) ; return ( ( sr - Math . floor ( sr ) ) == 0 ) ; } function findSubarraySum ( arr , n , k ) { let prevSum = new Map ( ) ; let res = 0 ; let currsum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { currsum += arr [ i ] ; if ( currsum == K ) { res ++ ; } if ( prevSum . has ( currsum - K ) ) res += ( prevSum . get ( currsum - K ) ) ; prevSum . set ( currsum , prevSum . get ( currsum ) == null ? 1 : prevSum . get ( currsum ) + 1 ) ; } return res ; } function countSubarray ( arr , n , k ) { for ( let i = 0 ; i < n ; i ++ ) { if ( isPerfectSquare ( arr [ i ] ) ) { arr [ i ] = 1 ; } else { arr [ i ] = 0 ; } } document . write ( findSubarraySum ( arr , n , K ) ) ; } let arr = [ 2 , 4 , 9 , 2 ] ; let K = 2 ; let N = arr . length ; countSubarray ( arr , N , K ) ;