Count Subarrays having Sum K
Last Updated :
26 Dec, 2024
Given an unsorted array of integers, the task is to find the number of subarrays having a sum exactly equal to a given number k.
Examples:
Input : arr[] = [10, 2, -2, -20, 10], k = -10
Output : 3
Explanation: Subarrays: arr[0...3], arr[1...4], arr[3...4] have sum equal to -10.
Input : arr[] = [9, 4, 20, 3, 10, 5], k = 33
Output : 2
Explanation: Subarrays: arr[0...2], arr[2...4] have sum equal to 33.
Input : arr[] = [1, 3, 5], k = 2
Output : 0
Explanation: No subarrays with 0 sum.
[Naive Approach] Using Nested Loop - O(n^2) Time and O(1) Space
A simple solution is to traverse all the subarrays and calculate their sum. If the sum is equal to the given number k, then increment the count of subarrays.
C++
// C++ program to count subarrays having sum K
// using nested loop
#include <iostream>
#include <vector>
using namespace std;
int countSubarrays(vector<int>& arr, int k) {
int res = 0;
// Pick a starting point of the subarray
for (int s = 0; s < arr.size(); s++) {
int sum = 0;
// Pick an ending point
for (int e = s; e < arr.size(); e++) {
sum += arr[e];
if (sum == k)
res++;
}
}
return res;
}
int main() {
vector<int> arr = {10, 2, -2, -20, 10};
int k = -10;
cout << countSubarrays(arr, k);
return 0;
}
C
// C program to count subarrays having sum K
// using nested loop
#include <stdio.h>
int countSubarrays(int arr[], int n, int k) {
int res = 0;
// Pick a starting point of the subarray
for (int s = 0; s < n; s++) {
int sum = 0;
// Pick an ending point
for (int e = s; e < n; e++) {
sum += arr[e];
if (sum == k)
res++;
}
}
return res;
}
int main() {
int arr[] = {10, 2, -2, -20, 10};
int k = -10;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", countSubarrays(arr, n, k));
return 0;
}
Java
// Java program to count subarrays having sum K
// using nested loop
import java.util.*;
class GfG {
static int countSubarrays(int[] arr, int k) {
int res = 0;
// Pick a starting point of the subarray
for (int s = 0; s < arr.length; s++) {
int sum = 0;
// Pick an ending point
for (int e = s; e < arr.length; e++) {
sum += arr[e];
if (sum == k)
res++;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {10, 2, -2, -20, 10};
int k = -10;
System.out.println(countSubarrays(arr, k));
}
}
Python
# Python program to count subarrays having sum K
# using nested loop
def countSubarrays(arr, k):
res = 0
# Pick a starting point of the subarray
for s in range(len(arr)):
sum = 0
# Pick an ending point
for e in range(s, len(arr)):
sum += arr[e]
if sum == k:
res += 1
return res
if __name__ == "__main__":
arr = [10, 2, -2, -20, 10]
k = -10
print(countSubarrays(arr, k))
C#
// C# program to count subarrays having sum K
// using nested loop
using System;
class GfG {
static int countSubarrays(int[] arr, int k) {
int res = 0;
// Pick a starting point of the subarray
for (int s = 0; s < arr.Length; s++) {
int sum = 0;
// Pick an ending point
for (int e = s; e < arr.Length; e++) {
sum += arr[e];
if (sum == k)
res++;
}
}
return res;
}
static void Main(string[] args) {
int[] arr = { 10, 2, -2, -20, 10 };
int k = -10;
Console.WriteLine(countSubarrays(arr, k));
}
}
JavaScript
// JavaScript program to count subarrays having sum K
// using nested loop
function countSubarrays(arr, k) {
let res = 0;
// Pick a starting point of the subarray
for (let s = 0; s < arr.length; s++) {
let sum = 0;
// Pick an ending point
for (let e = s; e < arr.length; e++) {
sum += arr[e];
if (sum === k)
res++;
}
}
return res;
}
// Driver Code
const arr = [10, 2, -2, -20, 10];
const k = -10;
console.log(countSubarrays(arr, k));
[Expected Approach] Using Hash Map and Prefix Sum - O(n) Time and O(n) Space
If you take a closer look at this problem, this is mainly an extension of Subarray with given sum.
The idea is to use a Hash Map to store the count of every prefix sum of the array. For each index i, with a current prefix sum currSum, we check if (currSum – k) exists in the map. If it does, it indicates the presence of a subarray ending at i with the given sum k. In such cases, we increment the result with the count of (currSum - k) stored in hash map.
C++
// C++ program to count subarrays having sum K
// using Hash Map
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
// Function to find number of subarrays with
// sum as k
int countSubarrays(vector<int> &arr, int k) {
// unordered_map to store prefix sums frequencies
unordered_map<int, int> prefixSums;
int res = 0;
int currSum = 0;
for (int i = 0; i < arr.size(); i++) {
// Add current element to sum so far.
currSum += arr[i];
// If currSum is equal to desired sum, then a new
// subarray is found. So increase count of subarrays.
if (currSum == k)
res++;
// Check if the difference exists in the prefixSums map.
if (prefixSums.find(currSum - k) != prefixSums.end())
res += prefixSums[currSum - k];
// Add currSum to the set of prefix sums.
prefixSums[currSum]++;
}
return res;
}
int main() {
vector<int> arr = {10, 2, -2, -20, 10};
int k = -10;
cout << countSubarrays(arr, k);
return 0;
}
Java
// Java program to count subarrays having sum K
// using Hash Map
import java.util.*;
class GfG {
// Function to find number of subarrays with sum as k
static int countSubarrays(int[] arr, int k) {
// HashMap to store prefix sums frequencies
Map<Integer, Integer> prefixSums = new HashMap<>();
int res = 0;
int currSum = 0;
for (int i = 0; i < arr.length; i++) {
// Add current element to sum so far.
currSum += arr[i];
// If currSum is equal to desired sum, then a new subarray is found.
if (currSum == k)
res++;
// Check if the difference exists in the prefixSums map.
if (prefixSums.containsKey(currSum - k))
res += prefixSums.get(currSum - k);
// Add currSum to the set of prefix sums.
prefixSums.put(currSum, prefixSums.getOrDefault(currSum, 0) + 1);
}
return res;
}
public static void main(String[] args) {
int[] arr = {10, 2, -2, -20, 10};
int k = -10;
System.out.println(countSubarrays(arr, k));
}
}
Python
# Python program to count subarrays having sum K
# using Hash Map
def countSubarrays(arr, k):
# Dictionary to store prefix sums frequencies
prefixSums = {}
res = 0
currSum = 0
for val in arr:
# Add current element to sum so far
currSum += val
# If currSum is equal to desired sum, then a new subarray is found
if currSum == k:
res += 1
# Check if the difference exists in the prefixSums dictionary
if currSum - k in prefixSums:
res += prefixSums[currSum - k]
# Add currSum to the dictionary of prefix sums
prefixSums[currSum] = prefixSums.get(currSum, 0) + 1
return res
if __name__ == "__main__":
arr = [10, 2, -2, -20, 10]
k = -10
print(countSubarrays(arr, k))
C#
// C# program to count subarrays having sum K
// using Hash Map
using System;
using System.Collections.Generic;
class GfG {
// Function to find number of subarrays with sum as k
static int countSubarrays(int[] arr, int k) {
// Dictionary to store prefix sums frequencies
Dictionary<int, int> prefixSums = new Dictionary<int, int>();
int res = 0;
int currSum = 0;
for (int i = 0; i < arr.Length; i++) {
// Add current element to sum so far
currSum += arr[i];
// If currSum is equal to desired sum, then a new subarray is found
if (currSum == k)
res++;
// Check if the difference exists in the prefixSums dictionary
if (prefixSums.ContainsKey(currSum - k))
res += prefixSums[currSum - k];
// Add currSum to the dictionary of prefix sums
if (!prefixSums.ContainsKey(currSum))
prefixSums[currSum] = 0;
prefixSums[currSum]++;
}
return res;
}
static void Main(string[] args) {
int[] arr = { 10, 2, -2, -20, 10 };
int k = -10;
Console.WriteLine(countSubarrays(arr, k));
}
}
JavaScript
// JavaScript program to count subarrays having sum K
// using Hash Map
function countSubarrays(arr, k) {
// Map to store prefix sums frequencies
const prefixSums = new Map();
let res = 0;
let currSum = 0;
for (let val of arr) {
// Add current element to sum so far
currSum += val;
// If currSum is equal to desired sum, then a new subarray is found
if (currSum === k)
res++;
// Check if the difference exists in the prefixSums map
if (prefixSums.has(currSum - k))
res += prefixSums.get(currSum - k);
// Add currSum to the map of prefix sums
prefixSums.set(currSum, (prefixSums.get(currSum) || 0) + 1);
}
return res;
}
// Driver Code
const arr = [10, 2, -2, -20, 10];
const k = -10;
console.log(countSubarrays(arr, k));
Similar Reads
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 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
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 given XOR Given an array of integers arr[] and a number k, the task is to count the number of subarrays having XOR of their elements as k.Examples: Input: arr[] = [4, 2, 2, 6, 4], k = 6Output: 4Explanation: The subarrays having XOR of their elements as 6 are [4, 2], [4, 2, 2, 6, 4], [2, 2, 6], and [6].Input:
10 min read
CSES Solutions - Subarray Sums I Given an array arr[] of N positive integers, your task is to count the number of subarrays having sum X. Examples: Input: N = 5, X = 7, arr[] = {2, 4, 1, 2, 7}Output: 3Explanation: There are 3 subarrays with sum = 7. Subarray {2, 4, 1}, sum = 2 + 4 + 1 = 7.Subarray {4, 1, 2}, sum = 4 + 1 + 2 = 7.Sub
8 min read
Count of subarrays having sum equal to its length | Set 2 Given an array arr[] of size N, the task is to find the number of subarrays having 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 the 6 suba
7 min read
CSES Solutions - Subarray Sums II Given an array arr[] of N integers, your task is to count the number of subarrays having sum X. Examples: Input: N = 5, X = 7, arr[] = {2, -1, 3, 5, -2}Output: 2Explanation: There are 2 subarrays with sum = 7. Subarray {-1, 3, 5}, sum = -1 + 3 + 5 = 7.Subarray {2, -1, 3, 5, 2}, sum = 2 - 1 + 3 + 5 +
6 min read
Number of subarrays having sum of the form k^m, m >= 0 Given an integer k and an array arr[], the task is to count the number of sub-arrays that have the sum equal to some positive integral power of k.Examples: Input: arr[] = { 2, 2, 2, 2 } K = 2 Output: 8 Sub-arrays with below indexes are valid: [1, 1], [2, 2], [3, 3], [4, 4], [1, 2], [2, 3], [3, 4], [
10 min read
Sum of Count of Unique Numbers in all Subarrays Given an array of n integers, the task is to count the sum of unique numbers in all subarrays. Examples: Input: [2, 1, 2]Output: 9Explanation: There are total 6 subarrays which are [2], [2, 1], [2, 1, 2], [1], [1, 2], [2]. The count of unique numbers in these subarrays is 1, 2, 2, 1, 2, 1 respective
15+ min read
Count of Subarrays with sum equals k in given Binary Array 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 = 2Output: 6Explanation: 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,
10 min read