Find a subarray of size K whose sum is a perfect square | Python3 program for the above approach ; Function to check if a given number is a perfect square or not ; Find square root of n ; Check if the square root is an integer or not ; Function to print the subarray whose sum is a perfect square ; Sum of first K elements ; If the first k elements have a sum as perfect square ; Iterate through the array ; If sum is perfect square ; If subarray not found ; Driver Code ; Given array ; Given subarray size K ; Function call
from math import sqrt , ceil , floor NEW_LINE def isPerfectSquare ( n ) : NEW_LINE INDENT sr = sqrt ( n ) NEW_LINE return ( ( sr - floor ( sr ) ) == 0 ) NEW_LINE DEDENT def SubarrayHavingPerfectSquare ( arr , k ) : NEW_LINE INDENT ans = [ 0 , 0 ] NEW_LINE sum = 0 NEW_LINE i = 0 NEW_LINE while i < k : NEW_LINE INDENT sum += arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT found = False NEW_LINE if ( isPerfectSquare ( sum ) ) : NEW_LINE INDENT ans [ 0 ] = 0 NEW_LINE ans [ 1 ] = i - 1 NEW_LINE DEDENT else : NEW_LINE INDENT for j in range ( i , len ( arr ) ) : NEW_LINE INDENT sum = sum + arr [ j ] - arr [ j - k ] NEW_LINE if ( isPerfectSquare ( sum ) ) : NEW_LINE INDENT found = True NEW_LINE ans [ 0 ] = j - k + 1 NEW_LINE ans [ 1 ] = j NEW_LINE DEDENT DEDENT for k in range ( ans [ 0 ] , ans [ 1 ] + 1 ) : NEW_LINE INDENT print ( arr [ k ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if ( found == False ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 20 , 34 , 51 , 10 , 99 , 87 , 23 , 45 ] NEW_LINE K = 3 NEW_LINE SubarrayHavingPerfectSquare ( arr , K ) NEW_LINE DEDENT