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; }
You may find this interesting. I modified the method to use longs to prevent integer overflow resulting in negative numbers.
Both of these methods work just fine for positive numbers. Even though the first one is much simpler, they both return the same count for the test array.
Additionally, the statement
Always returns 1 for positive arrays. This is because previous sums can never be re-encountered for positive only values.
That statement, and the one which computes
count
by taking a value from the map is to allow the array to contain both positive and negative numbers. And ths same is true a-k
and all positive values.For the following input:
The subarrays that sum to 3 are
Since adding negative numbers can result in previous sums, those need to be accounted for. The solution for positive values does not do this.
This will also work for all negative values. If
k
is positive,no
subarray will be found since all sums will be negative. Ifk
is negative one or more subarraysmay
possibly be found.