Last active
June 20, 2020 21:45
-
-
Save JyotinderSingh/ec437dbdb2fe1db44d540da53ac576d3 to your computer and use it in GitHub Desktop.
Subarray Sum Equals K - C++ Solution
This file contains hidden or 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
// https://leetcode.com/problems/subarray-sum-equals-k/ | |
class Solution { | |
public: | |
int subarraySum(vector<int> &nums, int k) | |
{ | |
unordered_map<int, int> map; | |
int count = 0; | |
// maintains sum of elements so far | |
int curr_sum = 0; | |
// map[0] = 1 helps tackle the case when curr_sum == k | |
// because curr_sum - k == 0 in that case, so it helps add that case to solution. | |
map[0] = 1; | |
for (int num: nums) | |
{ | |
// add the current element to curr_sum | |
curr_sum += num; | |
// if curr_sum - sum already exists in map | |
// we have found a subarray with the target sum | |
if (map[curr_sum - k]) | |
{ | |
count += map[curr_sum-k]; | |
// cout << "sum found between " << map[curr_sum - k] + 1 << " and " << i << endl; | |
} | |
map[curr_sum]++; | |
} | |
return count; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment