Subarray Sum Equals K

• The codes in the last approach:

if (map.containsKey(sum))
map.put(sum, map.get(sum) + 1);
else
map.put(sum, 1);

may be better like this:

map.put(sum, map.getOrDefault(sum, 0) + 1);

• @amoker I have updated the code. Thanks.

• Hi, in the last method, why I change the order of if and put, I will get an error? Since the case of k = 0?

• @FF_TI Yes only for k=0, it will give false result.

• @FF_TI No need of put(0,1):

``````public int subarraySum(int[] nums, int k) {
int count=0,sum=0;
Map<Integer,Integer> hm = new HashMap<>();
for(int i=0;i<nums.length;i++){
hm.put(sum, hm.getOrDefault(sum,0)+1);
sum+=nums[i];
count+=hm.getOrDefault((sum-k),0);
}
return count;
}``````

• Why is this tagged "Map"? What's the difference between that and the tag "Hash table"?

• In the hashmap solution, why we need to put(0, 1) at first?

• Would sliding window work for this problem? Where we expand window until we reach desired sum, then shrink window if necessary, if we see desired sum, update result count

• Disregard sliding window suggestion, I see now the problem states negative values are possible (which discounts the use of sliding window)

• I am not sure I understood the first paragraph of the third solution correctly.

Suppose you have "1, 2, 3, 4, 5" --> [ sum[0]=1, sum[1]=3, sum[2]=6, sum[3]=10, sum[4]=15]

According to your saying "if the cumulative sum upto two indices, say i and j is at a difference of k i.e. if sum[i] - sum[j] = k, the sum of elements lying between indices i and j is k."

so sum[3] - sum[1] = 10 - 3 = 7, which means the sum of elements lying between indices 3 and 1 is 7? what do you mean the sum of elements?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.