human
Write me a code to count subarrays such that remainder after dividing sum of elements by K gives count of elements and the other steps required given the following:
Count subarrays such that remainder after dividing sum of elements by K gives count of elements | Function to return the number of subarrays of the given array such that the remainder when dividing the sum of its elements by K is equal to the number of its elements.
To store prefix sum.
We are dealing with zero indexed array.
Taking modulus value.
Prefix sum.
To store the required answer , the left index and the right index.
To store si - i value.
Include sum.
Increment the right index.
If subarray has at least k elements.
Return the required answer.
Driver code.
Function call"
Solution in Python:
assistant
#Here is code to count subarrays such that remainder after dividing sum of elements by K gives count of elements and the other steps required.
 def sub_arrays ( a , n , k ) :
	sum = [ 0 for i in range ( n + 2 ) ]
	for i in range ( n ) :
		a [ i ] -= 1
		a [ i ] %= k
		sum [ i + 1 ] += sum [ i ] + a [ i ]
		sum [ i + 1 ] %= k
	ans = 0
	l = 0
	r = 0
	mp = dict ( )
	for i in range ( n + 1 ) :
		if sum [ i ] in mp :
			ans += mp [ sum [ i ] ]
		mp [ sum [ i ] ] = mp . get ( sum [ i ] , 0 ) + 1
		r += 1
		if ( r - l >= k ) :
			mp [ sum [ l ] ] -= 1
			l += 1
	return ans
a = [ 1 , 4 , 2 , 3 , 5 ]
n = len ( a )
k = 4
print ( sub_arrays ( a , n , k ) )