Skip to content

Commit

Permalink
Merge pull request #108 from Shubh-k04/patch-2
Browse files Browse the repository at this point in the history
 Adding interview Question "Number of Subarray"
  • Loading branch information
TharinduDilshan authored Oct 30, 2021
2 parents dabc7dd + 71150ce commit 967ac7f
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions Java/Algorithm/NumberOfSubarray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.
*/
import java.util.HashMap;
import java.util.Map;

public class NumberOfSubarray {
public int subarraySum(int[] nums, int k)
{
int curr_sum = 0;
int cnt = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
for(int i=0;i<nums.length;i++){
curr_sum += nums[i];
if(map.containsKey(curr_sum - k)){
cnt += map.get(curr_sum - k);
}
map.put(curr_sum, map.getOrDefault(curr_sum, 0) + 1);
}
return cnt;
}
}

0 comments on commit 967ac7f

Please sign in to comment.