Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save manjunathshiva/11ced8a9e08898ad91b1bd9d72824f3c to your computer and use it in GitHub Desktop.
Save manjunathshiva/11ced8a9e08898ad91b1bd9d72824f3c to your computer and use it in GitHub Desktop.
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
//For fast I/O in C++
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n = nums.size();
if(n==0)
return 0;
unordered_map<int,int> mymap; //Key = PrefixSUM, Value = Count of PrefixSUM.
int currSUM = 0;
int i = 0;
int count = 0;
while(i<n)
{
currSUM += nums[i];
if(currSUM == k) //We found a new subArray with SUM = k
count += 1;
if(mymap.find(currSUM-k)!=mymap.end())
count += mymap[currSUM-k];
mymap[currSUM] += 1;
i += 1;
}
return count;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment