Subarrays with sum K | Practice | GeeksforGeeks

Given an unsorted array of integers, find the number of continuous subarrays having sum exactly equal to a given number k.

Example 1:
Input:
N = 5
Arr = {10 , 2, -2, -20, 10}
k = -10
Output: 3
Explaination: 
Subarrays: arr[0...3], arr[1...4], arr[3..4]
have sum exactly equal to -10.

Example 2:
Input:
N = 6
Arr = {9, 4, 20, 3, 10, 5}
k = 33
Output: 2
Explaination: 
Subarrays : arr[0...2], arr[2...4] have sum
exactly equal to 33.

Your Task:
You don't need to read input or print anything. Your task is to complete the function findSubArraySum() which takes the array Arr[] and its size N and k as input parameters and returns the count of subarrays.

Expected Time Complexity: O(NlogN)
Expected Auxiliary Space: O(N)

Constraints:
1 ≤ N ≤ 2*104
-103 ≤ Arr[i] ≤ 103
-107 ≤ k ≤ 107
0
dipeshmakwane2 weeks ago
//Using hashing 
//O(N) solution and O(N) space 
 int findSubArraySum(int Arr[], int N, int k)
    {
        // code here
        int pre_sum=0;
        int count=0;
        unordered_map<int,int>um;
        for(int i=0;i<N;i++){
            pre_sum+=Arr[i];
             um[pre_sum]++;
             if(pre_sum==k){
                count++;
            }
            if(um.count(pre_sum-k)==1){
                count+=um[pre_sum-k];
            }
           
        }
        return count;
    }
0
siddhant073 weeks ago
//Using hashing 
//O(N) solution and O(N) space 
    int findSubArraySum(int Arr[], int N, int k)
    {
        unordered_map< int, int> mp;
        mp[0] = 1;
        int cnt = 0;
        int curr = 0;
        for(int i = 0; i < N; i++){
            curr += Arr[i];
            cnt += mp[curr - k];
            mp[curr]++;
        }
        return cnt;
    }
0
itachinamikaze2211 month ago
JAVA 
static int findSubArraySum(int Arr[], int N, int k)   {       HashMap<Integer, Integer> map =new HashMap<>();       int c=0;       int sum=0;       map.put(sum, 1);       for(int i=0;i<Arr.length;i++)       {           sum=sum+Arr[i];           if(map.containsKey(sum-k))           {               c=c+map.get(sum-k);           }           map.put(sum, map.getOrDefault(sum,0)+1);       }       return c;   }
0
sy9924551 month ago
class Solution
{
    static int findSubArraySum(int arr[], int n, int k)
    {
        HashMap<Integer,Integer> map = new HashMap<>();
        map.put(0,1);
        int currSum = 0;
        int cnt = 0;
        for(int i=0;i<n;i++){
            currSum+=arr[i];
            if(map.containsKey(currSum-k)){
                cnt+=map.get(currSum-k);
            }
            map.put(currSum , map.getOrDefault(currSum,0)+1);
        }
        return cnt;
    }
}
0
amanasati11 month ago
Here, we will be using a dictionary which if a key not present in it. Instead of raising the error, it will automatically creates the key and raises its value to 0.
Defaultdict is a module in collections library with same features mentioned above.
Python code:
from collections import defaultdict
class Solution:
    def findSubArraySum(self, Arr, N, k):
        # code here
        dic=defaultdict(lambda:0)
        l,i,s=0,0,0  #l= count, s=sum
        while i<N:
            s+=Arr[i]
            if s==k:
                l+=1
                
            if s-k in dic:
                l+=dic[s-k]
                
            dic[s]+=1
            i+=1
        return l
0
samad11 month ago
My Approach (1.2/4.4 ):Why Do we Have to use HashTable:Let us Consider a subarray within the array whose sum is let say ‘x’ and a subarray starting just after this subarray sums up to k , a[i,j]=x & a[j+1,l]=k (l be any positive number ≥ j+1 and less than the size of array) so a[i,l]=x+k.Main observation to take from here is if take the sum form the starting index and store in a hashmap for every index i and also check for every index if ‘sum-k’ is already present in the subarray or not (x+k-k→x) ,sum-k would have been present in the map if and only if my current value is x+k hence we'll be able to consider all the subarrays , the last point which we have to to take care is that there can be more than 1 ‘x’ in the array while taking the sum as our array contains negative values so we have to count all those x's in our answer , that's why we use a map instead of a set to also keep the count of x's we have previously encountered and then add it to the answer. 
class Solution
{
   static int findSubArraySum(int Arr[], int N, int k)
   {
       // code here
       HashMap<Integer,Integer> hm=new HashMap<>();
       hm.put(0,1);
       int sum=0,cnt=0;
       for(int i=0;i<Arr.length;i++){
           sum+=Arr[i];
           if( hm.containsKey(sum-k))cnt+=hm.get(sum-k);
           if(hm.containsKey(sum))hm.put(sum,hm.get(sum)+1);
           else hm.put(sum,1);
       }
       return cnt;
   }
}
 
0
gargnipungarg2 months ago
class Solution{   static int findSubArraySum(int nums[], int N, int k)   {       // code here       Map<Integer , Integer> freq = new HashMap<>();       int count=0, sum=0;       for(int i=0; i<nums.length ; i++){           sum+=nums[i];           if(sum==k) count++; //if sum equals target           if(freq.get(sum-k)!=null) count+= freq.get(sum-k); //to find middle subarrays           freq.put(sum, freq.getOrDefault(sum, 0)+1);
       }       return count;   }}
+1
kashyapjhon2 months ago
C++ Solution Time=(1.3/3.7):
int findSubArraySum(int Arr[], int N, int k)   {       // code here       unordered_map<int,int> u;       int c=0;        u.insert({0,1});       int pre[N];       pre[0]=Arr[0];       for(int i=1;i<N;i++){           pre[i]=pre[i-1]+Arr[i];       }              for(int i=0;i<N;i++){           auto it=u.find(pre[i]-k);           if(it!=u.end()){               c=c+it->second;           }           u[pre[i]]++;       }       return c;   }
0
anandkumarsatapathy2 months ago
Very Easy
int c= 0;               unordered_map<int,int> m;       int sum=0;       for(int i = 0;i<n;i++){           sum+=nums[i];           if(sum==k)               c++;           if(m.find(sum-k)!=m.end())               c+=m[sum-k];                      m[sum]++;       }       return c;
+1
gulshan992 months ago
int findSubArraySum(int Arr[], int N, int k)
    {
        // code here
        int sum=0;
        int count=0;
        unordered_map<int,int>mp;
        for(int i=0;i<N;i++)
        {
            sum+=Arr[i];
            if(sum==k)count++;
            if(mp[sum-k])
              count+=mp[sum-k];
            mp[sum]++;  
        }
        return count;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.