Check if a subarray of size K exists whose elements form a number divisible by 3 | Function to find the K size subarray ; Check if the first K elements forms a number which is divisible by 3 ; Using Sliding window technique ; Calculate sum of next K size subarray ; Check if sum is divisible by 3 ; Update the indices of the subarray ; If no such subarray is found ; Print the subarray ; Driver code ; Given array and K ; Function call
def findSubArray ( arr , k ) : NEW_LINE INDENT ans = [ ( 0 , 0 ) ] NEW_LINE sm = 0 NEW_LINE i = 0 NEW_LINE found = 0 NEW_LINE while ( i < k ) : NEW_LINE INDENT sm += arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT if ( sm % 3 == 0 ) : NEW_LINE INDENT ans = [ ( 0 , i - 1 ) ] NEW_LINE found = 1 NEW_LINE DEDENT for j in range ( i , len ( arr ) , 1 ) : NEW_LINE INDENT if ( found == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT sm = sm + arr [ j ] - arr [ j - k ] NEW_LINE if ( sm % 3 == 0 ) : NEW_LINE INDENT ans = [ ( j - k + 1 , j ) ] NEW_LINE found = 1 NEW_LINE DEDENT DEDENT if ( found == 0 ) : NEW_LINE INDENT ans = [ ( - 1 , 0 ) ] NEW_LINE DEDENT if ( ans [ 0 ] [ 0 ] == - 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( ans [ 0 ] [ 0 ] , ans [ 0 ] [ 1 ] + 1 , 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 84 , 23 , 45 , 12 , 56 , 82 ] NEW_LINE K = 3 NEW_LINE findSubArray ( arr , K ) NEW_LINE DEDENT