You are given a binary array 'arr' of length 'N' and an integer 'k'. Return the number of subarrays having the count of 1's equal to ‘k’.
Let the array 'arr' be: [1, 0, 1].
Let ‘k’ be: 1
Then the subarrays having the number of ones equal to ‘k’ will be: [1], [1,0], [0,1], [1].
The first line contains two single space-separated integers 'N' and 'k'.
The second line contains 'N' space-separated integers, denoting the elements of array 'arr'.
Output Format :
The output contains the number of subarrays with the count of 1's equal to ‘k’.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
4 2
1 1 0 1
3
The subarrays having the number of ones equal to 2 will be: [1,1], [1,1,0], [1,0,1].
So the count is 3.
5 1
1 0 0 1 0
9
1 <= 'N' <= 10^4
arr[i] is either 0 or 1.
0 <= 'k' <= 10^6
Time limit: 1 sec
Check for every possible subarray present in an array.
Approach:
This approach is a brute-force solution to count the number of subarrays with a given sum 'k' in the binary array 'arr'. It uses nested loops to check all possible subarrays, resulting in a less efficient algorithm.
Here is the algorithm:
O(N^2), where ‘N’ is the length of the given array.
The nested loops result in a time complexity of O(N^2) because for each index 'i', the algorithm iterates through all possible subarrays starting from that index.
O(1)
We don’t use any extra space. Therefore, the overall space complexity will be O(1).