VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-subarrays-with-sum-equals-k-in-given-binary-array/

⇱ Count of Subarrays with sum equals k in given Binary Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of Subarrays with sum equals k in given Binary Array

Last Updated : 8 Mar, 2026

Given a binary array arr[] and an integer k, find the count of non-empty subarrays with a sum equal to k.

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

Consider each subarray in the array and check if the sum is equal to the target.


Output
6

[Expected Approach] Using Sliding Window Approach - O(n) time and O(1) space

  • Use a sliding window with two pointers to count subarrays with sum ≤ k and ≤ k-1.
  • Expand the window to the right while the sum stays within the target limit.
  • For each position, the number of valid subarrays equals the distance between the two pointers.
  • The final answer is count(≤ k) − count(≤ k−1), which gives subarrays with sum exactly k.

Output
6
Comment
Article Tags: