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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read