CC-6 : Find Subarrays with sum k.
Description:
Given integer array arr, and target sum k, find the count of subarrays of arr that sum up to k.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| arr={2,3,2,4}; k=5; |
Count of subarrays with sum 5 is 2 |
| arr={2,3,2,2,4,1,3}; k=4; |
Count of subarrays with sum 4 is 3 |
Pseudocode:
| The java method should accept following input parameters: arr (integer array) and integer k (target sum). |
| Initialize a variable hMap of type HashMap |
| Initialize variable subArrSum to 0, we will use this variable to track subarray that sum up to k. |
| Initialize variable subArrayCnt to 0, we will use this variable to track number of subarrays that sum up to k. |
| Iterate through arr using a for loop with idx as a loop variable with initial value 0 and increment idx till it reaches arr.length-1:
Increment subArrSum by arr[idx].
If hMap does not contain key equal to subArrSum-k, then add 0 to subArrCnt.
If hMap contains key equal to subArrSum-k, then add value corresponding to key subArrSum-k to subArrCnt.
If hMap does not contain key equal to subArrSum, then add key subArrSum and add value 1 to hMap.
If hMap contains key equal to subArrSum, then add key subArrSum and add value equal to current value of key subArrSum, incremented by 1 to hMap.
|
| After completion of above loop, subArrCnt contains the count of subArrays that sum up to k. return subArrSum. |
Code:
public int hashMapSubarraysWithSumK(int[] arr, int k) throws Exception{
HashMap<Integer,Integer> sumMap=new HashMap<Integer, Integer>();
sumMap.put(0, 1); int subArrSum=0; int subArrCnt=0;
for (int idx=0; idx < arr.length; idx++) {
subArrSum=subArrSum+arr[idx];
subArrCnt=subArrCnt+sumMap.getOrDefault(subArrSum-k, 0);
sumMap.put(subArrSum, sumMap.getOrDefault(subArrSum, 0)+1);
}
return subArrCnt;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |