Forked from SuryaPratapK/Number of subarrays with sum equals K
Created
December 21, 2022 14:55
-
-
Save manjunathshiva/11ced8a9e08898ad91b1bd9d72824f3c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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