Friday, July 23, 2021

Subarray Sums Equals K

Problem:
Given an array of integers 'numsand an integer 'K', return the total number of continuous subarrays whose sum equals to 'K'.

Example, [1,2,3], K = 3, total subarray whose sum equal to 3 will be 2, thats are [1,2] and [3]


Approach:

We can solve this problem by a little observation, just think we need k - currnet value instead of k. We can maintain a prefix sum value and a "seen" hashmap, "seen" will tell us how many times we already found the  value we need (current prefix sum - K value)



Basicaly The Hashmap "Seen" we used as a frequency table, every time it store the occurences of 
current prefix sum - K value.

We collect the occurences of 
current prefix sum - K and we store in ans variable.

Now the question is why we need to count the occurences of the value we previously met !

See, in the second example the last Prefix value is 21,
now if we count 21-7 = 14 only 1 , thats not valid because if we include [-2,2] with [1,4] that will be another valid subarray.

When we search for 14 in Prefix sum array we find it on 2 and 4 indexes.
The logic here is that 14 + 7 = 21 so the array between indexes
~ 3 to 7 (-2 2 1 4 2)
~ 5 to 7 both have sum 7 ( 1 4 2)
The sum is still 7 in this case because there are negative numbers that balance up.
So if we consider count++ we will have one count less as we will consider only array 5 to 7 but now we know that 14 sum occured earlier too so even that needs to be added up so occurences of (sum-k).


Simple code:


No comments:

Post a Comment