Given a binary string str, the task is to find the count of K length subarrays containing only 1s.
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:
Please Login to comment...