Subarray Sum Equals K

Subarray Sum Equals K

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

LeetCode Problem - 560

import java.util.HashMap;
import java.util.Map;

class Solution {
    // Method to count the number of subarrays with a given sum
    public int subarraySum(int[] nums, int k) {
        int preSum = 0; // Initialize the prefix sum variable
        int result = 0; // Initialize the result variable
        Map<Integer, Integer> mp = new HashMap<>(); // Create a map to store prefix sums and their frequencies
        mp.put(0, 1); // Initialize the map with 0 sum having frequency 1

        // Loop through each element of the array
        for(int ele : nums){
            preSum += ele; // Update the prefix sum
            // Update the result by adding the frequency of prefix sum (preSum - k) if present in the map
            result += mp.getOrDefault(preSum - k, 0);
            // Update the frequency of current prefix sum in the map
            mp.put(preSum, mp.getOrDefault(preSum, 0) + 1);
        }

        // Return the final result
        return result;
    }
}