Count of subarrays having exactly K perfect square numbers | Python3 program to 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 ; STL 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
from collections import defaultdict NEW_LINE import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sr = math . sqrt ( x ) NEW_LINE return ( ( sr - math . floor ( sr ) ) == 0 ) NEW_LINE DEDENT def findSubarraySum ( arr , n , K ) : NEW_LINE INDENT prevSum = defaultdict ( int ) NEW_LINE res = 0 NEW_LINE currsum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT currsum += arr [ i ] NEW_LINE if ( currsum == K ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT if ( ( currsum - K ) in prevSum ) : NEW_LINE INDENT res += ( prevSum [ currsum - K ] ) NEW_LINE DEDENT prevSum [ currsum ] += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def countSubarray ( arr , n , K ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( isPerfectSquare ( arr [ i ] ) ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT DEDENT print ( findSubarraySum ( arr , n , K ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 9 , 2 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE countSubarray ( arr , N , K ) NEW_LINE DEDENT