The Wayback Machine - https://web.archive.org/web/20240830133629/https://www.geeksforgeeks.org/number-subarrays-sum-exactly-equal-k/
Open In App

Count Subarrays having Sum K

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
49.74%
34.6K

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>

Output
3

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>

Output
3

Time Complexity: O(n) 
Auxiliary Space: O(n)



Previous Article
Next Article

Similar Reads

Count subarrays having an equal count of 0s and 1s segregated
Given a binary array arr[], the task is to count the number of subarrays having equal count of 0s and 1s, and all the 0s and 1s are placed consecutively in that subarray. Examples: Input: arr[] = {1, 0, 1, 1}Output: 2Explanation: The subarrays satisfying the given conditions are {1, 0} and {0, 1}. Therefore, the count of such subarrays is 2. Input:
10 min read
Count subarrays having sum modulo K same as the length of the subarray
Given an integer K and an array arr[] consisting of N positive integers, the task is to find the number of subarrays whose sum modulo K is equal to the size of the subarray. Examples: Input: arr[] = {1, 4, 3, 2}, K = 3Output: 4Explanation: 1 % 3 = 1 (1 + 4) % 3 = 2 4 % 3 = 1 (3 + 2) % 3 = 2 Therefore, subarrays {1}, {1, 4}, {4}, {3, 2} satisfy the
15 min read
Count of subarrays having sum as a perfect cube
Given an array arr[], the task is to count the subarrays having sum as a perfect cube.Examples: Input: arr[] = {6, 10, 9, 2, 1, 113} Output: 3 Explanation: The subarrays with sum of elements equal to a perfect cube are: {1}. Therefore, sum of subarray = 1 (= 1^3).{6, 10, 9, 2}. Therefore, sum of subarray = 27 ( = 3^3).{9, 2, 1, 113}. Therefore, sum
6 min read
Count subarrays having sum of elements at even and odd positions equal
Given an array arr[] of integers, the task is to find the total count of subarrays such that the sum of elements at even position and sum of elements at the odd positions are equal. Examples: Input: arr[] = {1, 2, 3, 4, 1}Output: 1Explanation: {3, 4, 1} is the only subarray in which sum of elements at even position {3, 1} = sum of element at odd po
7 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 three subarrays have the number of elements equal
7 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 subarrays, following three subarrays satisfy the given
7 min read
Count of ways to split an Array into three contiguous Subarrays having increasing Sum
Given an array arr[] consisting of non-negative integers, the task is to find the number of ways to split the array into three non-empty contiguous subarrays such that their respective sum of elements are in increasing order. Examples: Input: arr[] = {2, 3, 1, 7} Output: 2 Explanation: {{2}, {3, 1}, {7}}, {{2}, {3}, {1, 7}} are the possible splits.
7 min read
Split array into K subarrays such that sum of maximum of all subarrays is maximized
Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print "-1". Examples: Input: arr[] = {5, 3, 2, 7, 6, 4},
11 min read
Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays
Given an array arr[] consisting of N integers, the task is to maximize the sum of the difference of the maximum and minimum in each subarrays by splitting the given array into non-overlapping subarrays. Examples: Input: arr[] = {8, 1, 7, 9, 2}Output: 14Explanation:Split the given array arr[] as {8, 1}, {7, 9, 2}. Now, the sum of the difference maxi
7 min read
Split into K subarrays to minimize the maximum sum of all subarrays
Given an Array[] of N elements and a number K. ( 1 &lt;= K &lt;= N ) . Split the given array into K subarrays (they must cover all the elements). The maximum subarray sum achievable out of K subarrays formed, must be the minimum possible. Find that possible subarray sum.Examples: Input : Array[] = {1, 2, 3, 4}, K = 3 Output : 4 Optimal Split is {1,
15 min read
Count of binary strings of length N having equal count of 0's and 1's and count of 1's &ge; count of 0's in each prefix substring
Given an integer N, the task is to find the number of possible binary strings of length N with an equal frequency of 0's and 1's in which frequency of 1's are greater or equal to the frequency of 0's in every prefix substring. Examples: Input: N = 2Output: 1Explanation:All possible binary strings of length 2 are {"00", "01", "10" and "11"}. Out of
7 min read
Count subarrays having each distinct element occurring at least twice
Given an array arr[] of size N, the task is to count the number of subarrays from the given array, such that each distinct element in these subarray occurs at least twice. Examples: Input: arr[] = {1, 1, 2, 2, 2}Output: 6Explanation: Subarrays having each element occurring at least twice are :{{1, 1}, {1, 1, 2, 2}, {1, 1, 2, 2, 2}, {2, 2}, {2, 2, 2
8 min read
Count of subarrays having exactly K prime numbers
Given an array arr[] of N integers and a number K. The task is to count the number of subarray with exactly K Prime Numbers.Example: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 4 Explanation: Since total number of prime number in the array are 2. So the 4 subarray with 2 prime number are: 1. {2, 3} 2. {1, 2, 3} 3. {2, 3, 4} 4. {1, 2, 3, 4}Input: arr
11 min read
Count of subarrays having exactly K perfect square numbers
Given a unsorted integer array arr[] and an integer K. The task is to count the number of subarray with exactly K Perfect Square Numbers. Examples: Input: arr[] = {2, 4, 9, 3}, K = 2 Output: 4 Explanation: Since total number of perfect square number in the array are 2. So the 4 subarrays with 2 perfect square number are: 1.{2, 4, 9} 2.{2, 4, 9, 3}
10 min read
Split an Array to maximize subarrays having equal count of odd and even elements for a cost not exceeding K
Given an array arr[] of size N and an integer K, the task is to split the given array into maximum possible subarrays having equal count of even and odd elements such that the cost to split the array does not exceed K. The cost to split an array into a subarray is the difference between the last and first elements of the subarrays respectively. Exa
8 min read
Count of subarrays of size K with elements having even frequencies
Given an array arr[] and an integer K, the task is to count subarrays of size K in which every element appears an even number of times in the subarray. Examples: Input: arr[] = {1, 4, 2, 10, 2, 10, 0, 20}, K = 4 Output: 1 Explanation: Only subarray {2, 10, 2, 10} satisfies the required condition. Input: arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20}, K = 3
9 min read
Count of subarrays of size K having at least one pair with absolute difference divisible by K-1
Given an arr[] consisting of N elements, the task is to count all subarrays of size K having atleast one pair whose absolute difference is divisible by K - 1.Examples: Input: arr[] = {1, 5, 3, 2, 17, 18}, K = 4 Output: 3 Explanation: The three subarrays of size 4 are: {1, 5, 3, 2}: Pair {5, 2} have difference divisible by 3 {5, 3, 2, 17}: Pairs {5,
4 min read
Count even length subarrays having bitwise XOR equal to 0
Given an array arr[] of size N, the task is to count all possible even length subarrays having bitwise XOR of subarray elements equal to 0. Examples: Input: arr[] = {2, 2, 3, 3, 6, 7, 8}Output: 3Explanation:Subarrays having XOR of elements equal to 0 are: {{2, 2}, {3, 3}, {2, 2, 3, 3}}Therefore, the required output is 3. Input: arr[] = {1, 2, 3, 3}
13 min read
Count subarrays having a single distinct element that can be obtained from a given array
Given an array arr[] of size N, the task is to count the number of subarrays consisting of a single distinct element that can be obtained from a given array. Examples: Input: N = 4, arr[] = { 2, 2, 2, 2 }Output: 7Explanation: All such subarrays {{2}, {2}, {2}, {2}, {2, 2}, {2, 2, 2}, {2, 2, 2, 2}}. Therefore, total count of such subarrays are 7. In
5 min read
Count subarrays having even Bitwise OR
Given an array arr[] consisting of N positive integers, the task is to count the number of subarrays whose Bitwise OR of its elements even. Examples: Input: arr[] = {1, 5, 4, 2, 6 }Output: 6Explanation:The subarrays with even Bitwise OR are {4}, {2}, {6}, {2, 6}, {4, 2}, {4, 2, 6}.Therefore, the number of subarrays having even Bitwise OR are 6. Inp
7 min read
Count subarrays having odd Bitwise XOR
Given an array arr[] of size N, the task is to count the number of subarrays from the given array having odd Bitwise XOR value. Examples: Input: arr[] = {1, 4, 7, 9, 10}Output: 8Explanation: The subarrays having odd Bitwise XOR are {1}, {1, 4}, {1, 4, 7, 9}, {1, 4, 7, 9, 10}, {7}, {9}, {4, 7}, {9, 10}. Input: arr[] ={1, 5, 6}Output: 3Explanation: T
11 min read
Count subarrays made up of elements having exactly K set bits
Given an array arr[] consisting of N integers and an integer K, the task is to count the number of subarrays possible consisting of elements having exactly K set bits. Examples: Input: arr[] = {4, 2, 1, 5, 6}, K = 2Output: 3Explanation: The subarrays made up of elements having exactly 2 set bits are {5}, {6} and {5, 6}. Input: arr[] = {4, 2, 1, 5,
7 min read
Count subarrays having exactly K elements occurring at least twice
Given an array arr[] consisting of N integers and a positive integer K, the task is to count the number of subarrays having exactly K elements occurring at least twice. Examples: Input: arr[] = {1, 1, 1, 2, 2}, K = 1Output: 7Explanation: The subarrays having exactly 1 element occurring at least twice are: {1, 1}. Frequency of 1 is 2.{1, 1, 1}. Freq
11 min read
Count of subarrays having product as a perfect cube
Given an array arr[] consisting of N positive integers, the task is to count the number of subarrays with product of its elements equal to a perfect cube. Examples: Input: arr[] = {1, 8, 4, 2}Output: 6Explanation:The subarrays with product of elements equal to a perfect cube are: {1}. Therefore, product of subarray = 1 (= (1)3).{1, 8}. Therefore, p
14 min read
Count subarrays having even Bitwise XOR
Given an array arr[] of size N, the task is to count the number of subarrays from the given array whose Bitwise XOR is even. Examples: Input: arr[] = {1, 2, 3, 4}Output: 4Explanation: The subarrays having even Bitwise XOR are {{2}, {4}, {1, 2, 3}, {1, 2, 3, 4}}. Input: arr[] = {2, 4, 6}Output: 6Explanation: The subarrays having even Bitwise XOR are
11 min read
Count subarrays having product equal to the power of a given Prime Number
Given an array arr[] of size N and an integer M, the task is to count the number of subarrays having product of its elements equal to the power of M, where M is a prime number. Examples: Input: arr[] = {2, 2, 2, 2}, M = 2Output: 10Explanation: All possible non-empty subarrays having product equal to the power of M = (4 * (4 + 1)) / 2 = 10 Input: ar
8 min read
Count ways to split array into three non-empty subarrays having equal Bitwise XOR values
Given an array arr[] consisting of N non-negative integers, the task is to count the number of ways to split the array into three different non-empty subarrays such that Bitwise XOR of each subarray is equal. Examples: Input: arr[] = {7, 0, 5, 2, 7} Output: 2Explanation: All possible ways are:{{7}, {0, 5, 2}, {7}} where XOR value of each subarray i
9 min read
Count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times
Given an array arr[] consisting of N integers, the task is to find the number of different sequences that can be formed after performing the below operation on the given array arr[] any number of times. Choose two indices i and j such that arr[i] is equal to arr[j] and update all the elements in the range [i, j] in the array to arr[i]. Examples: In
7 min read
Count of subarrays in range [L, R] having XOR + 1 equal to XOR (XOR) 1 for M queries
Given an array, arr[] of N positive integers and M queries which consist of two integers [Li, Ri] where 1 ? Li ? Ri ? N. For each query, find the number of subarrays in range [Li, Ri] for which (X+1)=(X?1) where X denotes the xor of a subarray. Input: arr[]= {1, 2, 9, 8, 7}, queries[] = {{1, 5}, {3, 4}}Output: 6 1Explanation: Query 1: L=1, R=5: sub
12 min read
Count subarrays having at least X distinct elements that occur exactly Y times
Given three integers N, X, Y, and an array arr[] of size N, the task is to find the count of subarrays having at least X distinct elements that occur only Y times. Example: Input: N = 9, X = 2, Y = 2, arr[] = {2, 1, 2, 5, 3, 1, 3, 2, 5}Output:10Explanation:Subarrays with at least X distinct elements occurring exactly Y times are: {2, 1, 2, 5, 3, 1}
8 min read
Practice Tags :