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
function sub_arrays ( a , n , k ) { let sum = new Array ( n + 2 ) ; for ( let i = 0 ; i < n + 2 ; i ++ ) { sum [ i ] = 0 ; } for ( let i = 0 ; i < n ; i ++ ) { a [ i ] -- ; a [ i ] %= k ; sum [ i + 1 ] += sum [ i ] + a [ i ] ; sum [ i + 1 ] %= k ; } let ans = 0 , l = 0 , r = 0 ; let mp = new Map ( ) ; for ( let i = 0 ; i < n + 1 ; i ++ ) { if ( ! mp . has ( sum [ i ] ) ) mp . set ( sum [ i ] , 0 ) ; } let temp ; for ( let i = 0 ; i < n + 1 ; i ++ ) { ans += mp . get ( sum [ i ] ) ; temp = mp . get ( sum [ i ] ) + 1 ; mp . set ( sum [ i ] , temp ) ; r ++ ; if ( r - l >= k ) { temp = mp . get ( sum [ l ] ) - 1 ; mp . set ( sum [ i ] , temp ) ; l ++ ; } } return ans ; } let a = [ 1 , 4 , 2 , 3 , 5 ] ; let n = a . length ; let k = 4 ; document . write ( sub_arrays ( a , n , k ) ) ;