Subarray Sum Equals K

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
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;
}
}




