I'm trying to understand the logic behind the following code however I'm unclear about 2 parts of the code partially because the math supporting the logic is not totally clear to me at this moment.
CONFUSION 1: I don't understand why would we put 0 with count = 1 in the map before we start finding the sum of the array? How does it help?
CONFUSION 2: If I move the
map.put(sum, map.getOrDefault(sum)+1)
after the if() condition, I get the correct solution. However if I put it at the place as shown in the code below, it gives me wrong result. The question is why does the position of this matters, when we're searching for the value of sum-k in the map for finding the countpublic int subarraySum(int[] nums, int k) { HashMap<Integer,Integer> prefixSumMap = new HashMap<>(); prefixSumMap.put(0, 1); // CONFUSION 1 int sum = 0; int count = 0; for(int i=0; i<nums.length; i++) { sum += nums[i]; prefixSumMap.put(sum, prefixSumMap.getOrDefault(sum, 0)+1); //CONFUSION 2 if(prefixSumMap.containsKey(sum - k)) { count += prefixSumMap.get(sum - k); } } return count; }