Count of Subarrays with sum equals k in given Binary Array
Last Updated :
16 May, 2025
Given a binary array arr[] and an integer k, the task is to find the count of non-empty subarrays with a sum equal to k.
Examples:
Input: arr[] = {1, 0, 1, 1, 0, 1}, k = 2
Output: 6
Explanation: All valid subarrays are: {1, 0, 1}, {0, 1, 1}, {1, 1}, {1, 0, 1}, {0, 1, 1, 0}, {1, 1, 0}.
Input: arr[] = {0, 0, 0, 0, 0}, k = 0
Output: 15
Explanation: All subarrays have a sum equal to 0, and there are a total of 15 subarrays.
[Naive Approach] Checking Each Subarray - O(n^2) time and O(1) space
The idea is to consider each subarray in the array and check if the sum is equal to the target.
C++
// C++ program to find count of Subarrays
// with sum equals k in given Binary Array
#include <iostream>
#include <vector>
using namespace std;
// Function to find count of subarrays
// with sum equal to k
int numberOfSubarrays(vector<int>& arr, int k) {
int ans = 0, n = arr.size();
// Check for each subarray
for (int i=0; i<n; i++) {
int sum = 0;
for (int j=i; j<n; j++) {
sum += arr[j];
if (sum == k) ans++;
}
}
return ans;
}
int main() {
vector<int> arr = { 1, 0, 1, 1, 0, 1 };
int k = 2;
cout << numberOfSubarrays(arr, k) << endl;
return 0;
}
Java
// Java program to find count of Subarrays
// with sum equals k in given Binary Array
class Main {
// Function to find count of subarrays
// with sum equal to k
static int numberOfSubarrays(int[] arr, int k) {
int ans = 0, n = arr.length;
// Check for each subarray
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
if (sum == k) ans++;
}
}
return ans;
}
public static void main(String[] args) {
int[] arr = {1, 0, 1, 1, 0, 1};
int k = 2;
System.out.println(numberOfSubarrays(arr, k));
}
}
Python
# Python program to find count of Subarrays
# with sum equals k in given Binary Array
# Function to find count of subarrays
# with sum equal to k
def numberOfSubarrays(arr, k):
ans = 0
n = len(arr)
# Check for each subarray
for i in range(n):
sum = 0
for j in range(i, n):
sum += arr[j]
if sum == k:
ans += 1
return ans
if __name__ == "__main__":
arr = [1, 0, 1, 1, 0, 1]
k = 2
print(numberOfSubarrays(arr, k))
C#
// C# program to find count of Subarrays
// with sum equals k in given Binary Array
using System;
class GfG {
// Function to find count of subarrays
// with sum equal to k
static int numberOfSubarrays(int[] arr, int k) {
int ans = 0, n = arr.Length;
// Check for each subarray
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
if (sum == k) ans++;
}
}
return ans;
}
static void Main() {
int[] arr = {1, 0, 1, 1, 0, 1};
int k = 2;
Console.WriteLine(numberOfSubarrays(arr, k));
}
}
JavaScript
// JavaScript program to find count of Subarrays
// with sum equals k in given Binary Array
// Function to find count of subarrays
// with sum equal to k
function numberOfSubarrays(arr, k) {
let ans = 0;
let n = arr.length;
// Check for each subarray
for (let i = 0; i < n; i++) {
let sum = 0;
for (let j = i; j < n; j++) {
sum += arr[j];
if (sum === k) ans++;
}
}
return ans;
}
let arr = [1, 0, 1, 1, 0, 1];
let k = 2;
console.log(numberOfSubarrays(arr, k));
[Expected Approach] Using Sliding Window Approach - O(n) time and O(1) space
The idea is to use a sliding window approach with two pointers to efficiently count the number of subarrays with sum equal to k. The key insight is that we can find subarrays with sum exactly equal to k by calculating the difference between the count of subarrays with sum at most k and the count of subarrays with sum at most k-1.
Step by step approach:
- Create a sliding window that expands rightward as long as adding the next element doesn't exceed the target sum.
- For each position of the left pointer, count how many valid subarrays start at that position.
- The number of valid subarrays starting at each position equals the distance between the two pointers.
- Remove the leftmost element from the window and shift the left pointer right.
- Subtract the count of subarrays with sum at most (k-1) from the count of subarrays with sum at most k to get the result.
C++
// C++ program to find count of Subarrays
// with sum equals k in given Binary Array
#include <iostream>
#include <vector>
using namespace std;
// Function to find count of subarrays
// with sum at most k
int atmost(vector<int>& arr, int k){
if (k < 0)
return 0;
int n = arr.size();
int res = 0, sum = 0, j = 0;
for (int i=0; i<n; i++) {
while (j < n && sum+arr[j] <= k) {
sum += arr[j];
j++;
}
// Number of sub-arrays starting from
// index i that have sum atmost k will
// be (j-i).
res += (j - i);
// Remove the i'th index from window.
sum -= arr[i];
}
return res;
}
// Function to find count of subarrays
// with sum equal to k
int numberOfSubarrays(vector<int>& arr, int k) {
// Call atmost(arr, k) and atmost
// (arr, k-1) to get the count of
// subarrays with sum at most k
// and sum at most k-1 respectively,
// then subtract them to get the count
// of subarrays with sum exactly
// equal to k
return atmost(arr, k) - atmost(arr, k - 1);
}
int main() {
vector<int> arr = { 1, 0, 1, 1, 0, 1 };
int k = 2;
cout << numberOfSubarrays(arr, k) << endl;
return 0;
}
Java
// Java program to find count of Subarrays
// with sum equals k in given Binary Array
import java.util.*;
class GfG {
// Function to find count of subarrays
// with sum at most k
static int atmost(int[] arr, int k) {
if (k < 0)
return 0;
int n = arr.length;
int res = 0, sum = 0, j = 0;
for (int i = 0; i < n; i++) {
while (j < n && sum + arr[j] <= k) {
sum += arr[j];
j++;
}
// Number of sub-arrays starting from
// index i that have sum atmost k will
// be (j-i).
res += (j - i);
// Remove the i'th index from window.
sum -= arr[i];
}
return res;
}
// Function to find count of subarrays
// with sum equal to k
static int numberOfSubarrays(int[] arr, int k) {
// Call atmost(arr, k) and atmost
// (arr, k-1) to get the count of
// subarrays with sum at most k
// and sum at most k-1 respectively,
// then subtract them to get the count
// of subarrays with sum exactly
// equal to k
return atmost(arr, k) - atmost(arr, k - 1);
}
public static void main(String[] args) {
int[] arr = {1, 0, 1, 1, 0, 1};
int k = 2;
System.out.println(numberOfSubarrays(arr, k));
}
}
Python
# Python program to find count of Subarrays
# with sum equals k in given Binary Array
# Function to find count of subarrays
# with sum at most k
def atmost(arr, k):
if k < 0:
return 0
n = len(arr)
res, sum_, j = 0, 0, 0
for i in range(n):
while j < n and sum_ + arr[j] <= k:
sum_ += arr[j]
j += 1
# Number of sub-arrays starting from
# index i that have sum atmost k will
# be (j-i).
res += (j - i)
# Remove the i'th index from window.
sum_ -= arr[i]
return res
# Function to find count of subarrays
# with sum equal to k
def numberOfSubarrays(arr, k):
# Call atmost(arr, k) and atmost
# (arr, k-1) to get the count of
# subarrays with sum at most k
# and sum at most k-1 respectively,
# then subtract them to get the count
# of subarrays with sum exactly
# equal to k
return atmost(arr, k) - atmost(arr, k - 1)
if __name__ == "__main__":
arr = [1, 0, 1, 1, 0, 1]
k = 2
print(numberOfSubarrays(arr, k))
C#
// C# program to find count of Subarrays
// with sum equals k in given Binary Array
using System;
class GfG {
// Function to find count of subarrays
// with sum at most k
static int atmost(int[] arr, int k) {
if (k < 0)
return 0;
int n = arr.Length;
int res = 0, sum = 0, j = 0;
for (int i = 0; i < n; i++) {
while (j < n && sum + arr[j] <= k) {
sum += arr[j];
j++;
}
// Number of sub-arrays starting from
// index i that have sum atmost k will
// be (j-i).
res += (j - i);
// Remove the i'th index from window.
sum -= arr[i];
}
return res;
}
// Function to find count of subarrays
// with sum equal to k
static int numberOfSubarrays(int[] arr, int k) {
// Call atmost(arr, k) and atmost
// (arr, k-1) to get the count of
// subarrays with sum at most k
// and sum at most k-1 respectively,
// then subtract them to get the count
// of subarrays with sum exactly
// equal to k
return atmost(arr, k) - atmost(arr, k - 1);
}
static void Main() {
int[] arr = {1, 0, 1, 1, 0, 1};
int k = 2;
Console.WriteLine(numberOfSubarrays(arr, k));
}
}
JavaScript
// JavaScript program to find count of Subarrays
// with sum equals k in given Binary Array
// Function to find count of subarrays
// with sum at most k
function atmost(arr, k) {
if (k < 0)
return 0;
let n = arr.length;
let res = 0, sum = 0, j = 0;
for (let i = 0; i < n; i++) {
while (j < n && sum + arr[j] <= k) {
sum += arr[j];
j++;
}
// Number of sub-arrays starting from
// index i that have sum atmost k will
// be (j-i).
res += (j - i);
// Remove the i'th index from window.
sum -= arr[i];
}
return res;
}
// Function to find count of subarrays
// with sum equal to k
function numberOfSubarrays(arr, k) {
// Call atmost(arr, k) and atmost
// (arr, k-1) to get the count of
// subarrays with sum at most k
// and sum at most k-1 respectively,
// then subtract them to get the count
// of subarrays with sum exactly
// equal to k
return atmost(arr, k) - atmost(arr, k - 1);
}
let arr = [1, 0, 1, 1, 0, 1];
let k = 2;
console.log(numberOfSubarrays(arr, k));
Similar Reads
Count Subarrays of 1 in Binary Array Given an array arr[] of size N, the array contains only 1s and 0s, and the task is to return the count of the total number of subarrays where all the elements of the subarrays are 1. Examples: Input: N = 4, arr[] = {1, 1, 1, 0}Output: 6Explanation: Subarrays of 1 will look like the following: [1], [
12 min read
Count pairs from given array with Bitwise OR equal to K Given an array arr[] consisting of N positive integers and an integer K, the task is to count all pairs possible from the given array with Bitwise OR equal to K. Examples: Input: arr[] = {2, 38, 44, 29, 62}, K = 46Output: 2Explanation: Only the following two pairs are present in the array whose Bitw
5 min read
Count of subarrays with sum at least K Given an array arr[] of size N and an integer K > 0. The task is to find the number of subarrays with sum at least K.Examples: Input: arr[] = {6, 1, 2, 7}, K = 10 Output: 2 {6, 1, 2, 7} and {1, 2, 7} are the only valid subarrays.Input: arr[] = {3, 3, 3}, K = 5 Output: 3 Approach: For a fixed left
6 min read
Count Subarrays With Sum Divisible By K Given an array arr[] and an integer k, the task is to count all subarrays whose sum is divisible by k.Examples: Input: arr[] = [4, 5, 0, -2, -3, 1], k = 5Output: 7Explanation: There are 7 subarrays whose sum is divisible by 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3] and [
9 min read
Count of subarrays which contains a given number exactly K times Given an array A[] of N elements consisting of values from 1 to N with duplicates, the task is to find the total number of subarrays that contain a given number num exactly K times. Examples: Input: A[] = {1, 2, 1, 5, 1}, num = 1, K = 2 Output: 2 Explanation: Subarrays {1, 2, 1, 5}, {1, 2, 1}, {2, 1
8 min read
Count of subarrays having sum equal to its length Given an array arr[] of size N, the task is to find the number of subarrays having the sum of its elements equal to the number of elements in it. Examples: Input: N = 3, arr[] = {1, 0, 2}Output: 3Explanation:Total number of subarrays are 6 i.e., {1}, {0}, {2}, {1, 0}, {0, 2}, {1, 0, 2}.Out of 6 only
7 min read