The Wayback Machine - https://web.archive.org/web/20211216083133/https://www.geeksforgeeks.org/count-of-k-length-subarrays-containing-only-1s-in-given-binary-string/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count of K length subarrays containing only 1s in given Binary String

  • Last Updated : 16 Dec, 2021

Given a binary string str, the task is to find the count of K length subarrays containing only 1s.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: str = “0101000”, K=1
Output: 2
Explanation: 0101000 -> There are 2 subarrays with 1 ones



Input: str = “11111001”, K=3
Output: 3

 

Approach: The task can be solved by keeping track of the group sizes of consecutive ones. Once, we get the groupSize, we can deduce that number of possible subarrays of length k, and all 1s, are groupSize – k + 1.

Follow the below steps to solve the problem:

  • Iterate over the binary string from the start
  • Increment the count, if 1 is encountered, and at a point where 0 comes. 
  • Store the current count to get the groupSize of consecutive 1s, and re-initialize the count to 0.
  • Add the count of possible subarrays of size k in this groupSize using relation groupSize – k + 1
  • Return the final sum of count.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the count of all possible
// k length subarrays
int get(string s, int k)
{
    // Add dummy character at last to handle
    // edge cases, where string ends with '1'
    s += '0';
    int n = s.length();
  
    int cnt = 0, ans = 0;
    for (int i = 0; i < n; i++) {
        if (s[i] == '1')
            cnt++;
        else {
            if (cnt >= k) {
                ans += (cnt - k + 1);
            }
            cnt = 0;
        }
    }
    return ans;
}
  
// Driver code
int main()
{
    string str = "0101000";
    int K = 1;
    cout << get(str, K) << endl;
    return 0;
}
Output
2

Time Complexity: O(N) 
Auxiliary Space: O(1) 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!