text: Count subarrays having sum modulo K same as the length of the subarray | Function that counts the subarrays having sum modulo k equal to the length of subarray ; Stores the count of subarrays ; Stores prefix sum of the array ; Calculate prefix sum array ; Generate all the subarrays ; Check if this subarray is a valid subarray or not ; Total count of subarrays ; Given arr [ ] ; Size of the array ; Given K ; Function Call
code: function countSubarrays ( a , n , k ) { var ans = 0 ; var pref = [ ] ; pref . push ( 0 ) ; for ( var i = 0 ; i < n ; i ++ ) pref . push ( ( a [ i ] + pref [ i ] ) % k ) ; for ( var i = 1 ; i <= n ; i ++ ) { for ( var j = i ; j <= n ; j ++ ) { if ( ( pref [ j ] - pref [ i - 1 ] + k ) % k == j - i + 1 ) { ans ++ ; } } } document . write ( ans + ' ' ) ; } var arr = [ 2 , 3 , 5 , 3 , 1 , 5 ] ; var N = arr . length ; var K = 4 ; countSubarrays ( arr , N , K ) ;