Count of substrings of a binary string containing K ones in C++

C++Server Side ProgrammingProgramming

We are given a string of binary numbers i.e. combination of 0’s and 1’s and an integer value k and the task is to calculate the count of substrings formed with the given binary string having given k 1’s.

Input − string str = ‘10000100000’, k = 2

Output − Count of substrings of a binary string containing K ones are − 6

Explanation − Substrings that can be formed from the given string are 1, 10, 100, 1000, 10000, 010, 100001, 10001, 1001, 101, 11, 1000010. So there are 6 substrings having k number of 1’s i.e. exactly 2 ones.

Input − string str = ‘10000100000’, k = 3

Output − Count of substrings of a binary string containing K ones are − 0

Explanation − We are given with an integer value of k as 3 and if we check our string containing binary numbers, it has only 2 ones. So there is no possibility of substring having given k number of ones.

The approach used in the below program is as follows

  • Input a string of binary numbers having combinations of 0’s and 1’s and an integer variable k.

  • Calculate the length of the string using length() function and pass the data to the function for further processing.

  • Declare a temporary variable count and total as 0 for storing the substrings with k ones.

  • Declare an array to store the frequency of ones of size as length of string plus one and initialise it with 0 and set the first element of array as 1.

  • Start loop FOR from 0 till the length of an array

  • Inside the loop, set total as total + str[i] - ‘0’. Check IF total >= k then set count as count + arr[total-k].

  • Return count

  • Print the result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int sub_k_ones(string str, int length, int k){
   int count = 0;
   int total_1 = 0;
   int arr_fre[length + 1] = {0};
   arr_fre[0] = 1;
   for (int i = 0; i < length; i++){
      total_1 = total_1 + (str[i] - '0');
      if (total_1 >= k){
         count = count + arr_fre[total_1 - k];
      }
      arr_fre[total_1]++;
   }
   return count;
}
int main(){
   string str = "10000100000";
   int length = str.length();
   int k = 2;
   cout<<"Count of substrings of a binary string containing K ones are: "<<sub_k_ones(str, length, k) << endl;
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of substrings of a binary string containing K ones are: 6
raja
Published on 02-Dec-2020 16:54:18
Advertisements