Count of substrings of a binary string containing K ones
Last Updated :
20 Jul, 2022
Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones.
Examples:
Input : s = “10010”
K = 1
Output : 9
The 9 substrings containing one 1 are,
“1”, “10”, “100”, “001”, “01”, “1”,
“10”, “0010” and “010”
In this problem we need to find count of substrings which contains exactly K ones or in other words sum of digits in those substring is K. We first create a prefix sum array and loop over that and stop when sum value is greater than or equal to K. Now if sum at current index is (K + a) then we know that substring sum, from all those indices where sum is (a), till current index will be K, so count of indices having sum (a), will be added to result. This procedure is explained with an example below,
string s = “100101”
K = 2
prefix sum array = [1, 1, 1, 2, 2, 3]
So, at index 3, we have prefix sum 2,
Now total indices from where sum is 2, is 1
so result = 1
Substring considered = [“1001”]
At index 4, we have prefix sum 2,
Now total indices from where sum is 2, is
1 so result = 2
Substring considered = [“1001”, “10010”]
At index 5, we have prefix sum 3,
Now total indices from where sum is 2,
is 3 so result = 5
Substring considered = [“1001”, “10010”,
“00101”, “0101”, “101”]
So we need to track two things, prefix sum and frequency of particular sum. In below code, instead of storing complete prefix sum, only prefix sum at current index is stored using one variable and frequency of sums in stored in an array. Total time complexity of solution is O(N).
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int countOfSubstringWithKOnes(string s, int K)
{
int N = s.length();
int res = 0;
int countOfOne = 0;
int freq[N + 1] = {0};
freq[0] = 1;
for ( int i = 0; i < N; i++) {
countOfOne += (s[i] - '0' );
if (countOfOne >= K) {
res += freq[countOfOne - K];
}
freq[countOfOne]++;
}
return res;
}
int main()
{
string s = "10010" ;
int K = 1;
cout << countOfSubstringWithKOnes(s, K) << endl;
return 0;
}
|
Java
import java.io.*;
public class GFG {
static int countOfSubstringWithKOnes(
String s, int K)
{
int N = s.length();
int res = 0 ;
int countOfOne = 0 ;
int []freq = new int [N+ 1 ];
freq[ 0 ] = 1 ;
for ( int i = 0 ; i < N; i++) {
countOfOne += (s.charAt(i) - '0' );
if (countOfOne >= K) {
res += freq[countOfOne - K];
}
freq[countOfOne]++;
}
return res;
}
static public void main (String[] args)
{
String s = "10010" ;
int K = 1 ;
System.out.println(
countOfSubstringWithKOnes(s, K));
}
}
|
Python3
def countOfSubstringWithKOnes(s, K):
N = len (s)
res = 0
countOfOne = 0
freq = [ 0 for i in range (N + 1 )]
freq[ 0 ] = 1
for i in range ( 0 , N, 1 ):
countOfOne + = ord (s[i]) - ord ( '0' )
if (countOfOne > = K):
res + = freq[countOfOne - K]
freq[countOfOne] + = 1
return res
if __name__ = = '__main__' :
s = "10010"
K = 1
print (countOfSubstringWithKOnes(s, K))
|
C#
using System;
public class GFG {
static int countOfSubstringWithKOnes(
string s, int K)
{
int N = s.Length;
int res = 0;
int countOfOne = 0;
int []freq = new int [N+1];
freq[0] = 1;
for ( int i = 0; i < N; i++) {
countOfOne += (s[i] - '0' );
if (countOfOne >= K) {
res += freq[countOfOne - K];
}
freq[countOfOne]++;
}
return res;
}
static public void Main ()
{
string s = "10010" ;
int K = 1;
Console.WriteLine(
countOfSubstringWithKOnes(s, K));
}
}
|
PHP
<?php
function countOfSubstringWithKOnes( $s , $K )
{
$N = strlen ( $s );
$res = 0;
$countOfOne = 0;
$freq = array ();
for ( $i = 0; $i <= $N ; $i ++)
$freq [ $i ] = 0;
$freq [0] = 1;
for ( $i = 0; $i < $N ; $i ++)
{
$countOfOne += ( $s [ $i ] - '0' );
if ( $countOfOne >= $K )
{
$res = $res + $freq [ $countOfOne - $K ];
}
$freq [ $countOfOne ]++;
}
return $res ;
}
$s = "10010" ;
$K = 1;
echo countOfSubstringWithKOnes( $s , $K ) , "\n" ;
?>
|
Javascript
<script>
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] - '0' );
if (countOfOne >= K)
{
res += freq[countOfOne - K];
}
freq[countOfOne]++;
}
return res;
}
let s = "10010" ;
let K = 1;
document.write(countOfSubstringWithKOnes(s, K));
</script>
|
Time Complexity: O(N).
Auxiliary Space: O(N).
Similar Reads
Count of substrings of a Binary string containing only 1s
Given a binary string of length N, we need to find out how many substrings of this string contain only 1s. Examples: Input: S = "0110111"Output: 9Explanation:There are 9 substring with only 1's characters. "1" comes 5 times. "11" comes 3 times. "111" comes 1 time. Input: S = "000"Output: 0 The_Appro
6 min read
Count N-length Binary Strings consisting of "11" as substring
Given a positive integer N, the task is to find the number of binary strings of length N which contains "11" as a substring. Examples: Input: N = 2Output: 1Explanation: The only string of length 2 that has "11" as a substring is "11". Input: N = 12Output: 3719 Approach: The idea is to derive the num
8 min read
Count of K length subarrays containing only 1s in given Binary String
Given a binary string str, the task is to find the count of K length subarrays containing only 1s. Examples: Input: str = "0101000", K=1Output: 2Explanation: 0101000 -> There are 2 subarrays with 1 ones Input: str = "11111001", K=3Output: 3 Approach: The task can be solved by keeping track of the
4 min read
Count number of substrings of a string consisting of same characters
Given a string. The task is to find out the number of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of su
6 min read
Count ways to generate Binary String not containing "0100" Substring
Given the number N, count the number of ways to create a binary string (the string that contains characters as zero or one) of size N such that it does not contain "0100" as a substring. A substring is a contiguous sequence of characters within a string. Examples: Input: N = 4Output: 15Explanation:
15+ min read
Count of substrings in a Binary String that contains more 1s than 0s
Given a binary string s, the task is to calculate the number of such substrings where the count of 1's is strictly greater than the count of 0's. Examples Input: S = "110011"Output: 11Explanation: Substrings in which the count of 1's is strictly greater than the count of 0's are { S[0]}, {S[0], S[1]
15+ min read
Count of substrings of a string containing another given string as a substring
Given two strings S and T, the task is to count the number of substrings of S that contains string T in it as a substring. Examples: Input: S = "dabc", T = "ab"Output: 4Explanation: Substrings of S containing T as a substring are: S[0, 2] = âdabâS[1, 2] = âabâS[1, 3] = âabcâS[0, 3] = âdabcâ Input: S
8 min read
Count of K length subarrays containing only 1s in given Binary String | Set 2
Given binary string str, the task is to find the count of K length subarrays containing only 1s. Examples Input: str = "0101000", K=1Output: 2Explanation: 0101000 -> There are 2 subarrays of length 1 containing only 1s. Input: str = "11111001", K=3Output: 3 Approach: The given problem can also be
4 min read
Count of setbits in bitwise OR of all K length substrings of given Binary String
Given a binary string str of length N, the task is to find the number of setbits in the bitwise OR of all the K length substrings of string str. Examples: Input: N = 4, K = 3, str = "1111"Output: 3Explanation: All 3-sized substrings of S are:"111" and "111". The OR of these strings is "111". Therefo
8 min read
Count of Reverse Bitonic Substrings in a given String
Given a string S, the task is to count the number of Reverse Bitonic Substrings in the given string. Reverse bitonic substring: A string in which the ASCII values of the characters of the string follow any of the following patterns: Strictly IncreasingStrictly decreasingDecreasing and then increasin
8 min read