Count of substrings of a binary string containing K ones | Method returns total number of substring having K ones ; Initialize index having zero sum as 1 ; Loop over binary characters of string ; Update countOfOne variable with value of ith character ; If value reaches more than K , then update result ; Add frequency of indices , having sum ( current sum - K ) , to the result ; Update frequency of one 's count ; Driver code
function countOfSubstringWithKOnes ( s , K ) { let N = s . length ; let res = 0 ; let countOfOne = 0 ; let freq = new Array ( N + 1 ) ; freq . fill ( 0 ) ; freq [ 0 ] = 1 ; for ( let i = 0 ; i < N ; i ++ ) { countOfOne += ( s [ i ] - ' ' ) ; if ( countOfOne >= K ) { res += freq [ countOfOne - K ] ; } freq [ countOfOne ] ++ ; } return res ; } let s = " " ; let K = 1 ; document . write ( countOfSubstringWithKOnes ( s , K ) ) ;