Count Subarrays having Sum K
Last Updated :
13 Aug, 2024
Given an unsorted array of integers, 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: arr[0…3], arr[1…4], arr[3..4] have sum -10.
Input : arr[] = {9, 4, 20, 3, 10, 5}, k = 33
Output : 2
Explanation: arr[0…2], arr[2…4] have sum 33.
Input : arr[] = {1, 3, 5}, k = 2
Output : 0
Explanation: No subarrays with 0 sum
Naive (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 required sum, then increment the count of subarrays.
C++
#include <bits/stdc++.h>
using namespace std;
int countSubarrays(vector<int>& arr, int k) {
int res = 0; // Initialize result
// Pick a starting point of the subarray
for (int s = 0; s < arr.size(); s++) {
int sum = 0; // Initialize sum
// 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 for the above approach
#include <stdio.h>
int main()
{
int arr[] = { 10, 2, -2, -20, 10 };
int k = -10;
int n = sizeof(arr) / sizeof(arr[0]);
int res = 0;
// Calculate all subarrays
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++)
{
// Calculate required sum
sum += arr[j];
// Check if sum is equal to required sum
if (sum == k)
res++;
}
}
printf("%d\n", res);
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java program for the above approach
import java.util.*;
class Solution {
public static void main(String[] args)
{
int arr[] = { 10, 2, -2, -20, 10 };
int k = -10;
int n = arr.length;
int res = 0;
// calculate all subarrays
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = i; j < n; j++) {
// calculate required sum
sum += arr[j];
// check if sum is equal to required sum
if (sum == k)
res++;
}
}
System.out.println(res);
}
}
// This code is contributed by Aditya Kumar (adityakumar129)
Python
# Python3 program for
# the above approach
# Calculate all subarrays
def count_all_subarrys(arr, n):
# count all subarrays
res = 0
for i in range(n):
summ = 0
for j in range(i, n):
# Calculate required sum
summ += arr[j]
# Check if sum is equal to
# required sum
if summ == k:
res += 1
return res
# main function
if __name__ == "__main__":
arr = [10, 2, -2, -20, 10]
n = len(arr)
k = -10
print(count_all_subarrys(arr, n))
# This code is contributed by shushant kumar
C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG {
static void Main() {
int[] arr = {10, 2, -2, -20, 10};
int k = -10;
int n = arr.Length;
int res = 0;
// Calculate all subarrays
for (int i = 0; i < n; i++)
{
int sum = 0;
for (int j = i; j < n; j++)
{
// Calculate required sum
sum += arr[j];
// Check if sum is equal to
// required sum
if (sum == k)
res++;
}
}
Console.WriteLine(res);
}
}
// This code is contributed by divyesh072019
JavaScript
<script>
// Javascript program for
// the above approach
let arr = [ 10, 2, -2, -20, 10 ];
let k = -10;
let n = arr.length;
let res = 0;
// Calculate all subarrays
for(let i = 0; i < n; i++)
{
let sum = 0;
for(let j = i; j < n; j++)
{
// Calculate required sum
sum += arr[j];
// Check if sum is equal to
// required sum
if (sum == k)
res++;
}
}
document.write(res);
// This code is contributed by suresh07
</script>
Time Complexity : O(n2)
Auxiliary Space: O(1)
Using HashSet and Prefix Sum (O(n) Time and Space):
If you take a closer look at this problem, this is mainly an extension of Subarray with given sum.
The idea is to store the sum of every prefix of the array in a HashSet, To check if there is a subarray with given sum check for every index i, and sum up to that index as currSum. If (currSum – sum) already exists in the hashmap, then a subarray with the given sum is found. We increment the result.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to find number of subarrays with
// sum as k.
int findSubarraySum(vector<int>& arr, int sum)
// unordered_set to store prefix sums.
unordered_set<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 == sum)
res++;
// If currSum exceeds the desired sum, check if
// the difference exists in the prefixSums set.
if (prefixSums.find(currSum - sum) != prefixSums.end())
res++;
// Add currSum to the set of prefix sums.
prefixSums.insert(currSum);
}
return res;
}
int main() {
vector<int> arr = {10, 2, -2, -20, 10};
int sum = -10;
cout << findSubarraySum(arr, sum);
return 0;
}
Java
// Java program to find number of subarrays
// with sum exactly equal to k.
import java.util.HashMap;
import java.util.Map;
public class GfG {
// Function to find number of subarrays
// with sum exactly equal to k.
static int findSubarraySum(int arr[], int n, int sum)
{
// HashMap to store number of subarrays
// starting from index zero having
// particular value of sum.
HashMap<Integer, Integer> prevSum = new HashMap<>();
prevSum.put(0,1);
int res = 0;
// Sum of elements so far.
int currSum = 0;
for (int i = 0; i < n; i++) {
// Add current element to sum so far.
currSum += arr[i];
//calculate the sum that have to be removed
//so that we can get the desired sum
int removeSum=currSum-sum;
//get count of occurrences of that sum that
//have to removed and add it to res value
if (prevSum.containsKey(removeSum))
res += prevSum.get(removeSum);
// Add currsum value to count of
// different values of sum.
prevSum.put(currSum,prevSum.getOrDefault(currSum,0)+1);
}
return res;
}
public static void main(String[] args)
{
int arr[] = { 10, 2, -2, -20, 10 };
int sum = -10;
int n = arr.length;
System.out.println(findSubarraySum(arr, n, sum));
}
}
// This code is contributed by Rituraj Jain
Python
# Python3 program to find the number of
# subarrays with sum exactly equal to k.
from collections import defaultdict
# Function to find number of subarrays
# with sum exactly equal to k.
def findSubarraySum(arr, n, Sum):
# Dictionary to store number of subarrays
# starting from index zero having
# particular value of sum.
prevSum = defaultdict(lambda : 0)
res = 0
# Sum of elements so far.
currsum = 0
for i in range(0, n):
# 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 == Sum:
res += 1
# currsum exceeds given sum by currsum - sum.
# Find number of subarrays having
# this sum and exclude those subarrays
# from currsum by increasing count by
# same amount.
if (currsum - Sum) in prevSum:
res += prevSum[currsum - Sum]
# Add currsum value to count of
# different values of sum.
prevSum[currsum] += 1
return res
if __name__ == "__main__":
arr = [10, 2, -2, -20, 10]
Sum = -10
n = len(arr)
print(findSubarraySum(arr, n, Sum))
# This code is contributed by Rituraj Jain
C#
// C# program to find number of subarrays
// with sum exactly equal to k.
using System;
using System.Collections.Generic;
class GFG {
// Function to find number of subarrays
// with sum exactly equal to k.
public static int findSubarraySum(int[] arr,
int n, int sum)
{
// HashMap to store number of subarrays
// starting from index zero having
// particular value of sum.
Dictionary<int, int> prevSum = new Dictionary<int, int>();
int res = 0;
// Sum of elements so far
int currsum = 0;
for (int i = 0; i < n; 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 == sum)
res++;
// currsum exceeds given sum by currsum
// - sum. Find number of subarrays having
// this sum and exclude those subarrays
// from currsum by increasing count by
// same amount.
if (prevSum.ContainsKey(currsum - sum))
res += prevSum[currsum - sum];
// Add currsum value to count of
// different values of sum.
if (!prevSum.ContainsKey(currsum))
prevSum.Add(currsum, 1);
else {
int count = prevSum[currsum];
prevSum[currsum] = count + 1;
}
}
return res;
}
// Driver Code
public static void Main()
{
int[] arr = { 10, 2, -2, -20, 10 };
int sum = -10;
int n = arr.Length;
Console.Write(findSubarraySum(arr, n, sum));
}
}
// This code is contributed by
// sanjeev2552
JavaScript
<script>
// Javascript program to find number of subarrays
// with sum exactly equal to k.
// Function to find number of subarrays
// with sum exactly equal to k.
function findSubarraySum(arr,n,sum)
{
// HashMap to store number of subarrays
// starting from index zero having
// particular value of sum.
let prevSum = new Map();
let res = 0;
// Sum of elements so far.
let currsum = 0;
for (let i = 0; i < n; 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 == sum)
res++;
// currsum exceeds given sum by currsum
// - sum. Find number of subarrays having
// this sum and exclude those subarrays
// from currsum by increasing count by
// same amount.
if (prevSum.has(currsum - sum))
res += prevSum.get(currsum - sum);
// Add currsum value to count of
// different values of sum.
let count = prevSum.get(currsum);
if (count == null)
prevSum.set(currsum, 1);
else
prevSum.set(currsum, count + 1);
}
return res;
}
let arr = [10, 2, -2, -20, 10];
let sum = -10;
let n = arr.length;
document.write(findSubarraySum(arr, n, sum));
// This code is contributed by avanitrachhadiya2155.
</script>
Time Complexity: O(n)
Auxiliary Space: O(n)
Please Login to comment...