I am trying to understand a program where the task is to find how many sub arrays are possible whose sum is equal to given value.
Here is the working code with O(N) complexity taken from link:
static int findSubarraySum(int arr[], int K) { Map<Integer, Integer> prevSum = new HashMap<>(); int res = 0; int currsum = 0; for (int i = 0; i < arr.length; i++) { currsum += arr[i]; if (currsum == K) res++; if (prevSum.containsKey(currsum - K)) res += prevSum.get(currsum - K); Integer count = prevSum.get(currsum); if (count == null) prevSum.put(currsum, 1); else prevSum.put(currsum, count + 1); } return res; } public static void main(String[] args) { int arr[] = {10, 2, -2, -20, 10}; int sum = -10; int n = arr.length; System.out.println(findSubarraySum(arr, sum)); } I am not able to understand the logic behind below code:
if (prevSum.containsKey(currsum - K)) res += prevSum.get(currsum - K); How the HashMap in above code is helpful in getting correct result.