Preview:
class Solution {
    public int subarraySum(int[] nums, int k) {
        //make prefix sum array and keep storing in HashMap
        //if at any moment (sum - k) exist in the array then the difference between 
        //sum & (sum - k) will be equal to k and that subarray will be equal to k 

        HashMap<Integer,Integer> map = new HashMap<>();
        
        int psa = 0 ,count = 0; //count is our answer , psa = prefix sum array
        map.put(0,1);           // adding 0 when pointer is at -1 index

        for(int i =0 ;i < nums.length ; i++){
            int val = nums[i];

            psa += val;

            if(map.containsKey(psa - k) ){
                count += map.get(psa-k);
            }

            map.put(psa , map.getOrDefault(psa,0)+1);
        }

        return count;
    }
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter