human
Write me a code to check if a subarray of size K exists whose elements form a number divisible by 3 and the other steps required given the following:
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"
Solution in Python:
assistant
#Here is code to check if a subarray of size K exists whose elements form a number divisible by 3 and the other steps required.
 def findSubArray ( arr , k ) :
	ans = [ ( 0 , 0 ) ]
	sm = 0
	i = 0
	found = 0
	while ( i < k ) :
		sm += arr [ i ]
		i += 1
	if ( sm % 3 == 0 ) :
		ans = [ ( 0 , i - 1 ) ]
		found = 1
	for j in range ( i , len ( arr ) , 1 ) :
		if ( found == 1 ) :
			break
		sm = sm + arr [ j ] - arr [ j - k ]
		if ( sm % 3 == 0 ) :
			ans = [ ( j - k + 1 , j ) ]
			found = 1
	if ( found == 0 ) :
		ans = [ ( - 1 , 0 ) ]
	if ( ans [ 0 ] [ 0 ] == - 1 ) :
		print ( - 1 )
	else :
		for i in range ( ans [ 0 ] [ 0 ] , ans [ 0 ] [ 1 ] + 1 , 1 ) :
			print ( arr [ i ] , end = " ▁ " )
if __name__ == ' _ _ main _ _ ' :
	arr = [ 84 , 23 , 45 , 12 , 56 , 82 ]
	K = 3
	findSubArray ( arr , K )